批改状态:合格
老师批语:
1. 类名的引用方式可以参考文件系统:绝对路径,相对路径,当前路径;类名也可以分为三种引用方式:
1)非限定名称
2)限额名称
3)完全限定名称
以下我们定义三个空间进行举例说明:
//父空间namespace father {class Test{}//1.非限定名称,相当于文件系统中的当前路径echo Test::class,"<br>";//2.限定名称,相当于文件系统中的相对路径echo son\Test::class,"<br>";//3.完全限定名称,相当于文件系统中的绝对路径echo \otherspace\Test::class,"<br>";}//子空间namespace father\son {class Test{}}//其它空间namespace otherspace {class Test{}}
在PHP中,别名是通过操作符 use 来实现的,使用别名的好处:1.简化,2.防止重名
例如:
namespace foo;//当前空间引用一个无自己无关联的类,需要使用完全限定名称:require 'homework1.php';$test = new \father\son\Test;var_dump($test);//运行结果:object(father\son\Test)#1 (0) { }// 使用别名,默认导入就是一个完全限定名称:use father\son\Test as Test;// 如果类别名和原始类名相同,可以省略://use father\son\Test; //效果等同于 use father\son\Test as Test;
如果导入类的原始类名与当前空间的类重名,那就不能省略了,例如:
class Test{}use father\son\Test as Demo;//使用不同别名避免冲突// 别名访问:$demo = new Demo;var_dump($demo);//object(father\son\Test)#2 (0) { }$test = new Test;var_dump($test);//object(foo\Test)#3 (0) { }
用sql_autoload_register()函数可以注册任意数量的自动加载器,将类空间名称与类文件所在的路径进行映射,实现自动加载
创建一个个类文件:config\models\CodModel.php, models\RegisterModel.php
config\models\CodModel.php内容如下:
<?phpnamespace config\models;class CodeModel{//....}
config\models\RegisterModel.php内容如下:
<?phpnamespace config\models;class RegisterModel{//...}
在config文件下写一个自动加载:
<?phpspl_autoload_register(function($class){//第一步:将空间分割符用DIRECTORY_SEPARATOR转为系统默认的路径分隔符//第二步:加上扩展名“.php“加载进来$file = str_replace('\\',DIRECTORY_SEPARATOR,$class).'.php';require $file;});
测试成果:
namespace config;//使用自动加载器:require 'config/loader.php';use config\models\CodeModel;use config\models\RegisterModel;$code = new CodeModel;$register = new RegisterModel;var_dump($code,$register);//运行结果:object(config\models\CodeModel)#2 (0) { } object(config\models\RegisterModel)#3 (0) { }
以建立一个新闻列表为例:
CREATE TABLE news (id int(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,title varchar(100) NOT NULL comment '标题',author varchar(20) NOT NULL comment '作者',content text NOT NULL comment '内容',created_at datetime NOT NULL comment '发表时间')ENGINE=InnoDB auto_increment=1 collate = utf8mb4_unicode_ci;
查看结构:
desc news;

查看有哪些表:
show tables;
查看建表语句:
show create table news;

删除字段:
alter table news drop created_at;
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号