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();
    }
}