PHP魔术方法__wakeup()

2018-09-17 15:00 By "Powerless" 3263 0 1

与__sleep()方法相对的就是__wakeup()方法,常用来反序列化,如重建数据连接,或执行其他初始化操作等。

示例代码如下:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    /**
     * @return array
     */
    public function __sleep() {
        echo "It is called when the serialize() method is called outside the class.<br>";
        $this->name = base64_encode($this->name);
        return array('name', 'age'); // 返回值中的元素必须是属性的名称
    }
    /**
     * __wakeup
     */
    public function __wakeup() {
        echo "It is called when the unserialize() method is called outside the class.<br>";
        $this->name = 2;
        $this->sex = 'Male';
        // 这里不需要返回数组
    }
}
$person = new Person('John'); // 赋初始值
var_dump(serialize($person));
var_dump(unserialize(serialize($person)));

输出结果如下:

It is called when the serialize() method is called outside the class.
string(58) "O:6:"Person":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}"
It is called when the unserialize() method is called outside the class.
object(Person)#2 (3) { ["sex"]=> string(3) "Male" ["name"]=> int(2) ["age"]=> int(25) }


评 论

View in WeChat

Others Discussion

  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56
  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15