本文實例分析了Thinkphp中的__initialize()和類的構(gòu)造函數(shù)__construct()。分享給大家供大家參考。具體分析如下:
thinkphp中的__construct是不可以隨便用的,因為你的模塊類繼承上級類,上級類有定義好的;
相關學習推薦:thinkphp
1、__initialize()不是php類中的函數(shù),php類的構(gòu)造函數(shù)只有__construct().
2、類的初始化:子類如果有自己的構(gòu)造函數(shù)(__construct()),則調(diào)用自己的進行初始化,如果沒有,則調(diào)用父類的構(gòu)造函數(shù)進行自己的初始化。
立即學習“PHP免費學習筆記(深入)”;
3、當子類和父類都有__construct()函數(shù)的時候,如果要在初始化子類的時候同時調(diào)用父類的__constrcut(),則可以在子類中使用parent::__construct().
如果我們寫兩個類,如下:
代碼如下:
class?Action{?? ????public?function?__construct()?? ????{?? ????????echo?'hello?Action';?? ????}?? }?? class?IndexAction?extends?Action{?? ????public?function?__construct()?? ????{?? ????????echo?'hello?IndexAction';?? ????}?? }?? $test?=?new?IndexAction;?? //output?---?hello?IndexAction
很明顯初始化子類IndexAction的時候會調(diào)用自己的構(gòu)造器,所以輸出是’hello IndexAction’,但是將子類修改為:
代碼如下:
class?IndexAction?extends?Action{?? ????public?function?__initialize()?? ????{?? ????????echo?'hello?IndexAction';?? ????}?? }
那么輸出的是’hello Action’,因為子類IndexAction沒有自己的構(gòu)造器,如果我想在初始化子類的時候,同時調(diào)用父類的構(gòu)造器呢?
代碼如下:
class?IndexAction?extends?Action{?? ????public?function?__construct()?? ????{?? ????????parent::__construct();?? ????????echo?'hello?IndexAction';?? ????}? ????}
這樣就可以將兩句話同時輸出,當然還有一種辦法就是在父類中調(diào)用子類的方法.
代碼如下:
class?Action{?? ????public?function?__construct()?? ????{?? ????????if(method_exists($this,'hello'))?? ????????{?? ????????????$this?->?hello();?? ????????}?? ????????echo?'hello?Action';?? ????}?? }?? class?IndexAction?extends?Action{?? ????public?function?hello()?? ????{?? ????????echo?'hello?IndexAction';?? ????}?? }
這樣也可以將兩句話同時輸出,而這里子類中的方法hello()就類似于ThinkPHP中__initialize()。
所以,ThinkPHP中的__initialize()的出現(xiàn)只是方便程序員在寫子類的時候避免頻繁的使用parent::__construct(),同時正確的調(diào)用框架內(nèi)父類的構(gòu)造器,所以,我們在ThnikPHP中初始化子類的時候要用__initialize(),而不用__construct(),當然你也可以通過修改框架將__initialize()函數(shù)修改為你喜歡的函數(shù)名.
相關推薦:編程視頻課程