批改状态:合格
老师批语:还在研究自动加载呢
1、写一个分级的命名空间, 并实现类的自动加载
目的:
1、相比于绝对路径引入类的文件路径,自动加载机制在当类库目录名或者文件名需要更改的时候,所有include了这个文件的php文件不需要随着修改,这避免了加大源代码目录结构重构的负担;
2、相比于在php.ini中的include_path引入类的文件路径,自动加载的机制可以节省很多性能问题;
3、类的查找顺序:优先查找手动include或require进来的类,查找不到的情况下再采用类的自动加载机制;
4、触发机制:触发的时机是,类不存在–》执行__spl_autoload_register函数–》报错
<?php
spl_autoload_register(function($className){
//file_exists() 函数检查文件或目录是否存在。
//str_replace() 函数以其他字符替换字符串中的一些字符(区分大小写)。
$path = str_replace('\\',DIRECTORY_SEPARATOR,$className);
$path=__DIR__.'/'.$path.'.php';
if(file_exists($path)){include $path;}
});
//访问本文件类类不到时,自动根据路径导入相关文件
echo \inc\Test1::get().'<br>';点击 "运行实例" 按钮查看在线实例
2、 写一个trait类, 理解它的功能与使用场景
<?php
//use PDO;
trait Db
{
public function connect($dsn,$username,$password)
{
return new PDO($dsn,$username,$password);
}
}
trait Query
{
public function get(PDO $pdo, $where = '')
{
$where = empty($where) ? '' : ' WHERE ' . $where;
$stmt = $pdo->prepare('SELECT * FROM `staff` '. $where . ' LIMIT 1');
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
class Client
{
use Db;
use Query;
public $pdo = null;
public function __construct($dsn,$username,$password)
{
$this->pdo = $this->connect($dsn,$username,$password);
}
public function find($where)
{
return $this-> get($this->pdo,$where);
}
}
$dsn='mysql:host=127.0.0.1;dbname=chenqingxuan';
$username='root';
$password='cqx07231950';
$obj = new Client($dsn,$username,$password);
var_dump($obj->find('age < 30')) ;点击 "运行实例" 按钮查看在线实例

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