国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > ThinkPHP > 正文

ThinkPHP __initialize()和類的構造函數__construct()剖析

2024-09-09 15:19:39
字體:
來源:轉載
供稿:網友

ThinkPHP中的__initialize()和類的構造函數__construct()

thinkphp中的__construct是不可以隨便用的,因為你的模塊類繼承上級類,上級類有定義好的;

1、__initialize()不是php類中的函數,php類的構造函數只有__construct().

2、類的初始化:子類如果有自己的構造函數(__construct()),則調用自己的進行初始化,如果沒有,則調用父類的構造函數進行自己的初始化。

3、當子類和父類都有__construct()函數的時候,如果要在初始化子類的時候同時調用父類的__constrcut(),則可以在子類中使用parent::__construct().

如果我們寫兩個類,如下:

  1. class Action{ 
  2.     public function __construct() 
  3.     { 
  4.         echo 'hello Action'
  5.     } 
  6. class IndexAction extends Action{ 
  7.     public function __construct() 
  8.     { 
  9.         echo 'hello IndexAction'
  10.     } 
  11. $test = new IndexAction; 
  12. //output --- hello IndexAction 

很明顯初始化子類IndexAction的時候會調用自己的構造器,所以輸出是'hello IndexAction',但是將子類修改為:

  1. class IndexAction extends Action{ 
  2.     public function __initialize() 
  3.     { 
  4.         echo 'hello IndexAction'
  5.     } 

那么輸出的是'hello Action',因為子類IndexAction沒有自己的構造器,如果我想在初始化子類的時候,同時調用父類的構造器呢?

  1. class IndexAction extends Action{ 
  2.     public function __construct() 
  3.     { 
  4.         parent::__construct(); 
  5.         echo 'hello IndexAction'
  6.     } 

這樣就可以將兩句話同時輸出,當然還有一種辦法就是在父類中調用子類的方法.

  1. class Action{ 
  2.     public function __construct() 
  3.     { 
  4.         if(method_exists($this,'hello')) 
  5.         { 
  6.             $this -> hello(); 
  7.         } 
  8.         echo 'hello Action'
  9.     } 
  10. class IndexAction extends Action{ 
  11.     public function hello() 
  12.     { 
  13.         echo 'hello IndexAction'
  14.     } 

這樣也可以將兩句話同時輸出,而這里子類中的方法hello()就類似于ThinkPHP中__initialize()。

所以,ThinkPHP中的__initialize()的出現只是方便程序員在寫子類的時候避免頻繁的使用parent::__construct(),同時正確的調用框架內父類的構造器,所以,我們在ThnikPHP中初始化子類的時候要用__initialize(),而不用__construct(),當然你也可以通過修改框架將__initialize()函數修改為你喜歡的函數名.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 甘孜县| 富裕县| 泽普县| 庄河市| 南陵县| 尚义县| 万年县| 岗巴县| 枝江市| 策勒县| 喀喇| 双辽市| 合川市| 淮南市| 仪征市| 尼勒克县| 保康县| 建德市| 白水县| 邵阳县| 略阳县| 东宁县| 息烽县| 门源| 光山县| 高雄市| 长岭县| 太康县| 连州市| 衢州市| 盐边县| 江口县| 瑞昌市| 台安县| 体育| 泸定县| 阳城县| 万年县| 紫金县| 临洮县| 五台县|