Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:匿名类的语法要注意
__sleep()
与wakeup()
实例演示、匿名类操作数据库__sleep()
与wakeup()
实例演示__sleep()
当对对象进行serialize()
序列化操作时,会调用类中的这个方法 然后将返回的数据进行序列化__wakeup()
当对序列化的对象进行unserialize()
反序列化操作时,会调用类中的这个方法
<?php
class Test{
private $name;
private $age;
public function __construct($n, $a){
$this->name = $n;
$this->age = $a;
}
public function __sleep(){
//返回一个数值 里边的元素表示返回的属性名称
return array('name');
}
public function __wakeup(){
$this->age = 30;
}
}
//实例化一个类
$test = new Test('peter', 20);
print_r($test);
echo '<hr>';
//序列化类对象
$seriTest = serialize($test);
print_r($seriTest);
echo '<hr>';
//反序列化
$test = unserialize($seriTest);
print_r($test);
<?php
//查找
$users = (new class('localhost', 'root', 'root', 'db_users'){
private $db = null;
public function __construct(...$params){
$this->db = new mysqli($params[0], $params[1], $params[2], $params[3]);
}
public function select(){
return $this->db->query('SELECT * FROM `user` LIMIT 2')->fetch_all(MYSQLI_ASSOC);
}
})->select();
print_r($users);
echo '<hr>';
//新增
$username = 'pdo';
$password = md5('pdo');
$age = 10;
$insertInfo = sprintf("username='%s', password='%s', age='%d'", $username, $password, $age);
$affect_rows = (new class('localhost', 'root', 'root', 'db_users'){
private $db;
public function __construct(...$params){
$this->db = new mysqli($params[0], $params[1], $params[2], $params[3]);
}
public function insert($info){
$this->db->query(sprintf('INSERT `user` SET %s', $info));
return $this->db->affected_rows;
}
})->insert($insertInfo);
echo "新增了{$affect_rows}行数据<hr>";
//更新
$username = 'pdo';
$password = md5('pdo');
$age = 10;
$updateInfo = sprintf("username='%s', password='%s', age='%d'", $username, $password, $age);
$condition = 'id=63';
$affect_rows = (new class('localhost', 'root', 'root', 'db_users'){
private $db;
public function __construct(...$params){
$this->db = new mysqli($params[0], $params[1], $params[2], $params[3]);
}
public function update($info, $cond){
$this->db->query(sprintf('UPDATE `user` SET %s WHERE %s', $info, $cond));
return $this->db->affected_rows;
}
})->update($updateInfo, $condition);
echo "更新了{$affect_rows}行数据<hr>";
//删除
$condition = 'id=103';
$affect_rows = (new class('localhost', 'root', 'root', 'db_users'){
private $db;
public function __construct(...$params){
$this->db = new mysqli($params[0], $params[1], $params[2], $params[3]);
}
public function delete($cond){
$this->db->query(sprintf('DELETE FROM `user` WHERE %s', $cond));
return $this->db->affected_rows;
}
})->delete($condition);
echo "删除了{$affect_rows}行数据<hr>";