批改状态:合格
老师批语:你也可以举一下其它形式的trait 类应用, 例如 模板加载
1. 写一个分级的命名空间, 并实现类的自动加载

<?php
namespace _1010;
use PDO as p;
interface iDbParams
{
const DSN = 'mysql:dbname=php';
const USER = 'root';
const PASS = 'root';
}
$pdo = new P(iDbParams::DSN, iDbParams::USER, iDbParams::PASS);
var_dump($pdo);
$sql = 'SELECT `staff_id`,`name`,`position` FROM `staff` LIMIT :num OFFSET :offset';
$stmt = $pdo->prepare($sql);
$stmt->bindValue('num',5,\PDO::PARAM_INT);
$stmt->bindValue('offset',0,\PDO::PARAM_INT);
$stmt->execute();
foreach ($stmt->fetchAll() as $staff){
echo "<p>{$staff['staff_id']} -- {$staff['name']} -- {$staff['position']}</p>";
}
exit;
?>点击 "运行实例" 按钮查看在线实例
2. 写一个trait类, 理解它的功能与使用场景

<?php
namespace _1010;
use PDO;
// trait
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
{
// 在宿主类Client中引入上面生命的二个Trait类/方法库
use Db;
use Query;
public $pdo = null;
public function __construct($dsn, $username, $password)
{
// 调用的是Trait Db中的方法connect()
$this->pdo = $this->connect($dsn, $username, $password);
}
// 调用的是Trait: Query中的方法:get()
public function find($where)
{
return $this->get($this->pdo,$where);
}
}
$dsn = 'mysql:dbname=php';
$username = 'root';
$password = 'root';
$client = new Client($dsn, $username, $password);
echo '<pre>' . print_r($client->find('age > 30'),true);
?>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号