標籤:解構函式 資料 初始化 ott www name new 刪除 his
__sleep:在serialize被調用時,被自動的調用
__wakeup:在unserialize別調用時,被自動的調用,可用於做對象的初始化操作
class A{ public $var; //serialize時被調用,當你不需要儲存大對象的所有資料時很有用 public function __sleep() { echo ‘__sleep called‘.PHP_EOL; return array(‘var‘); } //unserialize時被調用,可用於做些對象的初始化操作 public function __wakeup() { echo ‘__wakeup called‘.PHP_EOL; $this->var = ‘test after wakeup‘; }}$a = new A;var_dump(serialize($a));var_dump(unserialize(serialize($a)));
#########################################
__sleep called
E:\wamp64\www\test\test.php:142:string ‘O:1:"A":1:{s:3:"var";N;}‘ (length=24)__sleep called __wakeup called
E:\wamp64\www\test\test.php:143:object(A)[2] public ‘var‘ => string ‘test after wakeup‘ (length=17) public ‘var1‘ => null public ‘var2‘ => null
__toString:當一個類被轉換成字串時被調用
class TestClass{ public $foo; /** * 對象被轉化成字串輸出 * 一個類被當成字串時應怎樣回應 * @return mixed */ public function __toString() { return "toString called"; }}echo new TestClass();
__construct:建構函式的類會在每次建立新對象時先調用此方法,一般用於動態注入屬性。如果子類中定義了建構函式則不會隱式調用其父類的建構函式。要執行父類的建構函式,需要在子類的建構函式中調用 parent::__construct()。如果子類沒有定義建構函式則會如同一個普通的類方法一樣從父類繼承
__destruct:解構函式會在到某個對象的所有引用都被刪除或者當對象被顯式銷毀時執行。和建構函式一樣,父類的解構函式不會被引擎暗中調用。要執行父類的解構函式,必須在子類的解構函式體中顯式調用 parent::__destruct()。此外也和建構函式一樣,子類如果自己沒有定義解構函式則會繼承父類的。
class MyDestructableClass { function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "\n"; }}$obj = new MyDestructableClass();
PHP魔術方法