批改状态:合格
老师批语:实现类自动加载的方案有不少, 不一定完全一致的
// 1. 写一个分级的命名空间, 并实现类的自动加载

demo2.php文件
<?php
namespace int;
//自动加载函数
spl_autoload_register(function ($className){
//str_replace 字符串替换函数 (被替换的字符,DIRECTORY_SEPARATOR,字符串)
//DIRECTORY_SEPARATOR 系统目录分隔符
$path = str_replace('\\', DIRECTORY_SEPARATOR, $className);
$path = __DIR__ . '/' . $path . '.php';
//file_exists 检查如果$path文件存在,则加载此文件1次
if(file_exists($path)) include_once $path;
});
echo Test::demo();点击 "运行实例" 按钮查看在线实例
test.php文件
<?php
namespace int;
class Test
{
public static function demo()
{
return __METHOD__;
}
}点击 "运行实例" 按钮查看在线实例
// 2. 写一个trait类, 理解它的功能与使用场景

<?php
//子类 > trait > 父类
namespace _1010;
trait Db
{
public function connect($dsn, $username, $pwd)
{
return new \PDO($dsn, $username, $pwd);
}
}
trait Query
{
public function get($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
{
//在宿主类Client中引入上面声明的两个Trait类/方法集
use Db;
use Query;
public $pdo = null;
public function __construct($dsn,$username,$pwd)
{
$this->pdo = $this->connect($dsn,$username,$pwd);
}
public function find($where)
{
return $this->get($this->pdo,$where);
}
}
$dsn = 'mysql:dbname=staff';
$username = 'root';
$pwd = 'root';
$client = new Client($dsn,$username,$pwd);
echo '<pre>' . print_r($client->find('age>30'),true);点击 "运行实例" 按钮查看在线实例
小结:
1、自动加载,可以实现只需用到才加载,不用不加载,这样使程序运行更好;
2、trait使用级别,子类>trait>父类;trait也是方法集,使用trait好处市可以保存框架源码。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号