天天看點

ThinkPHP之__construct()和__initialize()

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

網上有很多關于__initialize()的說法和用法,總感覺不對頭,是以自己測試了一下。将結果和大家分享。不對請更正。

首先,我要說的是

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

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

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

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

[php]  view plain  copy  print ?

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

很明顯初始化子類IndexAction的時候會調用自己的構造器,是以輸出是'hello IndexAction'。

但是将子類修改為

[php]  view plain  copy  print ?

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

那麼輸出的是'hello Action'。因為子類IndexAction沒有自己的構造器。

如果我想在初始化子類的時候,同時調用父類的構造器呢?

[php]  view plain  copy  print ?

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

這樣就可以将兩句話同時輸出。

當然還有一種辦法就是在父類中調用子類的方法。

[php]  view plain  copy  print ?

  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. }  
  11. class IndexAction extends Action{  
  12.     public function hello()  
  13.     {  
  14.         echo 'hello IndexAction';  
  15.     }  
  16. }  

這樣也可以将兩句話同時輸出。

而,這裡子類中的方法hello()就類似于ThinkPHP中__initialize()。

是以,ThinkPHP中的__initialize()的出現隻是友善程式員在寫子類的時候避免頻繁的使用parent::__construct(),同時正确的調用架構内父類的構造器,是以,我們在ThnikPHP中初始化子類的時候要用__initialize(),而不用__construct(),當然你也可以通過修改架構将__initialize()函數修改為你喜歡的函數名。