批改状态:合格
老师批语:
- 实例演示通过空间引用类的三种方式;
- 类的别名引入与命名冲突的解决方案是什么?
- 写一个自动加载类;
- 将课堂提到的数据库操作命令全部上机做一遍,选择一些你认为有意思 很重要的发布到博客作业中…
// 实例演示通过空间引用类的三种方式namespace Ns {class Demo{}// 非限定名称:当前路径,类名前无空间前缀// Ns\Demoecho Demo::class, '<br>';// 限定名称:相对路径,类名前非全局开始的空间前缀// Ns\Ns2\Demoecho Ns2\Demo::class, '<br>';// 完全限定名称:绝对路径,类名前全局开始的空间前缀// Ns2\Demoecho \Ns2\Demo::class, '<br>';}namespace Ns\Ns2 {class Demo{}}namespace Ns2 {class Demo{}}*

使用别名
新建两个 php 文件,0223-1.php 0223-2.php
// 0223-1.phpnamespace Ns1 {// 导入 Ns2require '0223-2.php';// 使用别名区别当前空间同名的类名use \Ns2\Demo as Demo2;class Demo{public $file = '0223-1.php';}// 当前空间类// 0223-1.phpecho (new Demo)->file, '<br>';// 导入的空间类// 0223-2.phpecho (new Demo2)->file, '<br>';}
// 0223-2.phpnamespace Ns2 {class Demo{public $file = '0223-2.php';}}

// 类自动加载器spl_autoload_register(function ($class) {$path = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';if (!is_file($path)) {throw new \Exception($class);}require_once $path;});
新建目录 Ns2 复制 0223-2.php 改为和类名相同的 Demo.php,适配类名空间自动加载的目录结构
0223-1.php 注释导入的 0223-2.php 修改为导入自动加载器 autoloader.php
// 0223-1.phpnamespace Ns1 {// 导入 Ns2// require '0223-2.php';require 'autoloader.php';// 使用别名区别当前空间同名的类名use \Ns2\Demo as Demo2;class Demo{public $file = '0223-1.php';}// 当前空间类名// 0223-1.phpecho (new Demo)->file, '<br>';// 导入的空间类名// 0223-2.phpecho (new Demo2)->file, '<br>';}

-- 创建数据库 phpeducreate database phpedu collate utf8mb4_unicode_ci;-- 删除数据库 testdrop database test;-- 创建数据表 staffscreate table staffs(id int unsigned auto_increment not null primary key comment 'ID',name varchar(20) not null comment '姓名',gender enum('male', 'female') not null comment '性别',email varchar(120) not null comment '邮箱',birthday date not null comment '生日',create_at timestamp not null default current_timestamp comment '创建时间',update_at timestamp not null default current_timestamp on update current_timestamp comment '更新时间') engine = innodb auto_increment=1 collate=utf8mb4_unicode_ci;-- 删除数据表 testdrop table test-- 查看建表语句 staffsshow create table staffs-- 查看数据表show tables-- 查看表结构 staffsdesc staffs-- 添加表字段 salaryalter table staffs add salary int unsigned not null default 2000 after gender;-- 修改表字段 salaryalter table staffs change salary salary float not null default 1760 after gender;-- 删除表字段 testalter table staffs drop test;-- 表插入数据insert staffs (name, gender, salary, email, birthday) values('张三', 'male', 5000.00, 'a@b.cc', '1980-01-01'),('李四', 'female', 9999.99, 'b@a.cc', '1990-12-31');-- 子查询插入(数据全复制插入)insert staffs (name, gender, salary, email, birthday) select name, gender, salary, email, birthday from staffs;

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号