序列化和匿名类的演示
序列化和反序列化后自动连接数据库
序列化对象
<?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>';
匿名类(一次性,类的声明,实例,类的访问3合1)-阅后继焚
<?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.还没有理解到匿名类的应用场景(如果只用一次可以不用创建类直接写代码,如果用多次就直接创建一个类?)