PHP魔術方法

來源:互聯網
上載者:User

標籤:解構函式   資料   初始化   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魔術方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.