Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:因为在php中不存在类表达式的概念, 所以匿名类一定程度上起到这个作业, 不仅仅是一次性那么简单的, 匿名类可以当成值使用,可以当成函数的参数放在回调上使用, 场景非常丰富的
<?php
class Demo
{
public $params = [];
public $db;
public function __construct($dsn, $username, $password)
{
$this->params['dsn'] = $dsn;
$this->params['username'] = $username;
$this->params['password'] = $password;
$this->connect();
}
private function connect()
{
$this->db = new PDO(...array_values($this->params));
}
public function __sleep()
{
return ['params'];
}
}
$demo = new Demo('mysql:host=localhost;dbname=user', 'root', 'root');
file_put_contents('abc.txt', serialize($a));
<?php
class Demo
{
private $db;
public function __wakeup()
{
$this->db = new PDO(...array_values($this->params));
}
public function select($sql)
{
return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
}
// 反序列并自动连接数据库
$demo = unserialize(file_get_contents('PDO.txt'));
echo '<pre>' . print_r($demo->select('select * from apple limit 3'), true) . '</pre>';
<?php
// 1.实现接口功能
interface iDb
{
public function __construct($params);
}
// PDO查询
echo '<pre>' . print_r((new class (['mysql:host=localhost;dbname=user', 'root', 'root']) implements iDb
{
public $db;
public function __construct($params)
{
$this->db = new PDO(...$params);
}
function select($sql)
{
return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
})->select('select * from apple limit 3'), true) . '</pre>';
// PDO新增
echo '新增成功' . ((new class (['mysql:host=localhost;dbname=user', 'root', 'root']) implements iDb
{
public $db;
public function __construct($params)
{
$this->db = new PDO(...$params);
}
function insert($sql)
{
return $this->db->query($sql)->rowCount();
}
})->insert("insert apple set `username`='超时空',`password`=sha1(111),`sex`='男'")) . '条数据<hr>';
// PDO更新操作
echo '更新成功' . ((new class (['mysql:host=localhost;dbname=user', 'root', 'root']) implements iDb
{
public $db;
public function __construct($params)
{
$this->db = new PDO(...$params);
}
function update($sql)
{
return $this->db->query($sql)->rowCount();
}
})->update("update apple set `username`='光恶魔',`password`=sha1(111),`sex`='男' where `id`=51")) . '条数据<hr>';
// PDO删除
echo '删除成功' . ((new class (['mysql:host=localhost;dbname=user', 'root', 'root']) implements iDb
{
public $db;
public function __construct($params)
{
$this->db = new PDO(...$params);
}
function delete($sql)
{
return $this->db->query($sql)->rowCount();
}
})->delete("delete from apple where `id`=22")) . '条数据<hr>';
1.了解了序列化的一些应用
2.还没有理解到匿名类的应用场景(如果只用一次可以不用创建类直接写代码,如果用多次就直接创建一个类?)