php4中類比類的解構函式執行個體分析

來源:互聯網
上載者:User
最近做的一個項目是基於PHP4的, 習慣了PHP5的面對對象,面對PHP4,難免會有很多不爽:

不支援public, static, private, protected關鍵字, 最鬱悶的是,不支援解構函式:

本文就將藉助PHP的register_shutdown_function來在PHP4中類比類的解構函式

我們在建構函式中, 註冊解構函式:

class sample{   var $identified;   function sample($iden){       $this->identified = $iden;      register_shutdown_function(array(&$this, 'destructor')); //類比解構函式    }   function destructor(){     error_log("destructor executing, Iden is ". $this->identified);     unset($this);   }}  $sample = new sample("laruence"); $sample2 = new sample("HuiXinchen");

執行這個指令碼, 你會發現, 對象的解構函式被正確的調用了.
因為我們在註冊關閉函數的時候,使用了$this關鍵字, 所以,即使你的對面變數被覆蓋了, 解構函式也是可以被正確調用的,比如:

class sample{   var $identified;   function sample($iden){       $this->identified = $iden;      register_shutdown_function(array(&$this, 'destructor')); //類比解構函式    }   function destructor(){     error_log("destructor executing, Iden is ". $this->identified);     unset($this);   }}  $sample = new sample("laruence");  $sample = "laruence"; //覆蓋物件變數

$sample被覆蓋,但是運行這段指令碼,你會發現解構函式還是可以被正確調用. 即使是下面的代碼:

class sample{   var $identified;   function sample($iden){       $this->identified = $iden;      register_shutdown_function(array(&$this, 'destructor')); //類比解構函式    }   function destructor(){     error_log("destructor executing, Iden is ". $this->identified);     unset($this);   }}  $sample = new sample("laruence"); unset($sample);

解構函式還是可以被正確調用.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.