对象序列化与sleep(), wackup()
class lei
{
protected $name = '王小飞';
public $sex = '男';
protected $age = 20;
private $isMarried = false;
//__sleep()返回自定义的属性
public function __sleep(): array
{
return ['age', 'sex'];
}
//__wakeup()更新属性值
public function __wakeup()
{
$this->age = 26;
$this->sex = '不告诉你';
}
}
$lei = new lei();
//打印自定义属性
echo serialize($lei);
//把序列化内容保存变量里面
$xulie = serialize($lei);
//字符串打印反序列化 更新属性
var_dump(unserialize($xulie));
匿名类案例
function ff(object $user, string $name)
{
return $user->write($name);
}
//new一个匿名类
echo ff(new class (){
public function write($name)
{
return '你好' . $name;
}
}, '王小飞');
总结:感觉越来越难了,继续加油!