8315

[PHP] 類別的繼承及建構子和解構子

“
PHP 類別的繼承及建構子和解構子
„

分享此文連結 //n.sfs.tw/10582

分享連結 [PHP] 類別的繼承及建構子和解構子@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 02:52:22 最後編修
2017-01-09 11:49:02 By 張○○
 

自動目錄

1. php 的建構子

php 的建構子會在類別實體化(也就是new之後)後執行,寫法有兩種,一個是用 __construct() 保留字,另一個是用和類別同名的函式

class BASE{
   function __construct(){
      print "BASE constructor";
   }
}

或是

class BASE{
   function BASE(){
      print "constructor function same name with class";
   }
}

若同時有兩個建構子,則以  __construct() 為優先,同類別名的函數將不會被執行。

我個人建議使用 __construct(),因為類別可能因為改名或複製,常會忘記把建構子也改名。

class BASE{
   function BASE(){
      print "constructor function same name with class";
   }
   function __construct(){
      print "BASE constructed";
   }
}

執行結果:
BASE constructor

2. php 的解構子

php 的解構子會在1程式執行到結尾 2程式exit 3物件被unset 後被執行,寫法用 __desctruct() 保留字

class BASE{
   function __construct(){
      print "BASE constructedn";
   }
   function __destruct(){
      print "BASE destructedn";
   }
}

執行:

$obj =new BASE();
unset($obj);   <== 物件被 unset
print "ENDn";
exit;

結果
BASE constructed
BASE destructed
END

3. 建構和解構函數只不過是一個函數,預設是 public,都可以被叫用。


夏天的白雲特別白

4. 子類別繼承父類別後,父類別的建解構子都不會被執行

曾經我在這被卡了很久,因為別的語言(java, c#)會去叫用父類別的建解樣子後再處理子類別的。


class BASE{
   function BASE(){
      print "constructor function same name with class";
   }
   function __destruct(){
      print "BASE destructed";
   }
}

class CHILD extends BASE{
   function __construct(){
     print "CHILD constructed";
   }
   function __destruct(){
     print "CHILD destructed";
   }
}

執行
$obj =new CHILD();
exit;

結果
CHILD constructed
CHILD destructed

5. 子類別要執行父類別的建解構子,就要特別叫用,使用 parent:: 保留字

class BASE{
   function BASE(){
      print "constructor function same name with class";
   }
   function __destruct(){
      print "BASE destructed";
   }
}

class CHILD extends BASE{
   function __construct(){
     parent::__construct();
     print "CHILD constructed";
   }
   function __destruct(){
     parent::__destruct();
     print "CHILD destructed";
   }
}

執行
$obj =new CHILD();
exit;

結果
constructor function same name with class
CHILD constructed
BASE destructed
CHILD destructed

以上小小經驗分享


原文 2011-06-07 21:24:13

END

你可能感興趣的文章

[CodeIgniter 3] COOKIE的使用 PHP CodeIgniter 3 中COOKIE的使用超簡單

PHP 產生連續的日期 要用PHP產生連續的日期,連續月份

[PHP] 使用browscap檢查瀏覽器版本 使用PHP內建函數browscap檢查瀏覽器版本

[PHP] 輸出EXCEL的最簡易方法 輸出EXCEL最簡易方法,就沒要求太多了

[CodeIgniter 3] 資料庫的使用方法整理1/2 --Select的使用 [CodeIgniter 3] 資料庫的使用方法整理:Select的使用

PHP判斷對方瀏覽器語系 多語系的網頁應該主動偵查瀏覽器的語系,配合使用者跳出合適的語系。

隨機好文

使用Google尋找你的手機 這近發現google竟然可以用來找android的手機,而且不需要經過什麼設定或安裝軟體。

談借錢 人借錢時手心向上頭向下,人還錢時手心向下頭向上

SELinux 常用指令和檔案 在Redhat系列中,Centos5以後加入了selinux,他並沒有這麼可怕,不必每次看到Selinux ,就想把他

好用的3+2碼郵遞區號查詢系統推薦 網路上找到用地址輸入判斷3+2碼郵遞區號的辨識率不高,除了這個網站…

魔球中小女孩唱的歌 The show 魔球中小女孩唱的歌 The show

精讚::