PHP類和對象之建構函式和解構函式

來源:互聯網
上載者:User

標籤:cti   ons   初始化   構造   子類   類構造   bsp   const   extend   

PHP5可以在類中使用__construct()定義一個建構函式,具有建構函式的類,會在每次對象建立的時候調用該函數,因此常用來在對象建立的時候進行一些初始化工作。

class Car {   function __construct() {       print "建構函式被調用\n";   }}$car = new Car(); //執行個體化的時候 會自動調用建構函式__construct,這裡會輸出一個字串

在子類中如果定義了__construct則不會調用父類的__construct,如果需要同時調用父類的建構函式,需要使用parent::__construct()顯式的調用。

class Car {   function __construct() {       print "父類建構函式被調用\n";   }}class Truck extends Car {   function __construct() {       print "子類建構函式被調用\n";       parent::__construct();   }}$car = new Truck();

同樣,PHP5支援解構函式,使用__destruct()進行定義,解構函式指的是當某個對象的所有引用被刪除,或者對象被顯式的銷毀時會執行的函數。

class Car {   function __construct() {       print "建構函式被調用 \n";   }   function __destruct() {       print "解構函式被調用 \n";   }}$car = new Car(); //執行個體化時會調用建構函式echo ‘使用後,準備銷毀car對象 \n‘;unset($car); //銷毀時會調用解構函式

當PHP代碼執行完畢以後,會自動回收與銷毀對象,因此一般情況下不需要顯式的去銷毀對象。

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.