php魔术方法__sleep()

serialize() 函数会检查类中是否存在一个魔术方法 __sleep()。如果存在,则该方法会优先被调用,然后才执行序列化操作。

此功能可以用于清理对象,并返回一个包含对象中所有应被序列化的变量名称的数组。

如果该方法未返回任何内容,则 NULL 被序列化,并产生一个 E_NOTICE 级别的错误。

注意:__sleep() 不能返回父类的私有成员的名字。这样做会产生一个 E_NOTICE 级别的错误。可以用 Serializable 接口来替代。

作用:__sleep() 方法常用于提交未提交的数据,或类似的清理操作。同时,如果有一些很大的对象,但不需要全部保存,这个功能就很好用。

实例:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;

    public function __construct($name=\"\",  $age=25, $sex=\'男\')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }

    /**
     * @return array
     */
    public function __sleep() {
        echo \"当在类外部使用serialize()时会调用这里的__sleep()方法<br>\";
        $this->name =  64_encode($this->name);
        return array(\'name\', \'age\'); // 这里必须返回一个数值,里边的元素表示返回的属性名称
    }
}

$person = new Person(\'小明\'); // 初始赋值
echo serialize($person);
echo \'<br/>\';

代码运行结果:

当在类外部使用serialize()时会调用这里的__sleep()方法
O:6:\"Person\":2:{s:4:\"name\";s:8:\"5bCP5piO\";s:3:\"age\";i:25;}

 

php魔术方法__wakeup()

如果说 __sleep() 是白的,那么 __wakeup() 就是黑的了。

那么为什么呢?因为与之相反,`unserialize()` 会检查是否存在一个 `__wakeup()` 方法。如果存在,则会先调用 `__wakeup` 方法,预先准备对象需要的资源。

作用:__wakeup() 经常用在反序列化操作中,例如重新建立数据库连接,或执行其它初始化操作。

实例:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;

    public function __construct($name=\"\",  $age=25, $sex=\'男\')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }

    /**
     * @return array  码农教程  http://www.manongjc.com
     */
    public function __sleep() {
        echo \"当在类外部使用serialize()时会调用这里的__sleep()方法<br>\";
        $this->name =  64_encode($this->name);
        return array(\'name\', \'age\'); // 这里必须返回一个数值,里边的元素表示返回的属性名称
    }

    /**
     * __wakeup
     */
    public function __wakeup() {
        echo \"当在类外部使用unserialize()时会调用这里的__wakeup()方法<br>\";
        $this->name = 2;
        $this->sex = \'男\';
        // 这里不需要返回数组
    }
}

$person = new Person(\'小明\'); // 初始赋值
var_dump(serialize($person));
var_dump(unserialize(serialize($person)));

运行结果:

当在类外部使用serialize()时会调用这里的__sleep()方法
string(58) \"O:6:\"Person\":2:{s:4:\"name\";s:8:\"5bCP5piO\";s:3:\"age\";i:25;}\" 当在类外部使用serialize()时会调用这里的__sleep()方法
当在类外部使用unserialize()时会调用这里的__wakeup()方法
 (Person)#2 (3) { [\"sex\"]=> string(3) \"男\" [\"name\"]=> int(2) [\"age\"]=> int(25) }
收藏 打印