sleep() 和 wakeup()

__sleep__wakeup 是与序列化过程相关的方法。serialize 函数检查类是否有 __sleep 方法。如果是这样,它将在任何序列化之前执行。__sleep 应该返回一个应该序列化的对象的所有变量的名称数组。

如果 unserialize 出现在课堂上,则 __wakeup 将由 unserialize 执行。它的目的是重新建立在反序列化时需要初始化的资源和其他东西。

class Sleepy {
    public $tableName;
    public $tableFields;
    public $dbConnection;

    /**
     * This magic method will be invoked by serialize function.
     * Note that $dbConnection is excluded.
     */
    public function __sleep()
    {
        // Only $this->tableName and $this->tableFields will be serialized.
        return ['tableName', 'tableFields'];
    }

    /**
     * This magic method will be called by unserialize function.
     *
     * For sake of example, lets assume that $this->c, which was not serialized,
     * is some kind of a database connection. So on wake up it will get reconnected.
     */
    public function __wakeup()
    {
        // Connect to some default database and store handler/wrapper returned into
        // $this->dbConnection
        $this->dbConnection = DB::connect();
    }
}