[精讚] [會員登入]
7915

[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

你可能感興趣的文章

[phpmyadmin] 缺少 mcrypt 外掛,請檢查 PHP 設定 缺少 mcrypt 外掛,請檢查 PHP 設定,安裝php-mcrypt。

[PHP] 取得檔名和路徑:basename, dirname 由絕對路徑取的路徑及檔名的方法

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

[PHP] 讀取作業系統程式執行結果 PHP讀取作業系統程式執行結果

[PHP] 陣列新增資料及整理 在php陣列加入項目和重新整理陣列的方法

[PHP] CodeIgniter 3+pure+smarty安裝及環境設置2/2 PHP framework CodeIgniter 3+ pure CSS +smarty Template Engine的整合#2

隨機好文

UTF-8 BOM (Byte Order Mark) 的問題 在 Michael Kaplan 那看到 Every character has a story #4: U+feff

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

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?

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

APACHE的記錄檔格式 LogFormat 語法 在APACHE中有定義一些記錄的語法模版 在 /etc/httpd/conf/httpd.conf 中: LogForm