PHP __sleep()和__wakeup()

示例

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

__wakeupunserialize如果存在于类中,则依次执行。目的是重新建立在非序列化时需要初始化的资源和其他内容。

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()
    {
        // 连接到一些默认数据库并将存储的处理程序/包装返回
        // $this->dbConnection
        $this->dbConnection = DB::connect();
    }
}