ThinkPHP中_initialize()與__construct()用法

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

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

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

如果我們寫兩個類,如下

 代碼如下 複製代碼

class Action {
   public function __construct(){
       echo 'hello Action';
   }
}   

class IndexAcion extends Action {
   public function __construct(){
       echo 'hello,IndexAction';
   }
}

$test = new IndexAcion();
output --- hello IndexAction

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

 代碼如下 複製代碼
class IndexAcion extends Action {
   public function _initialize(){
       echo 'hello IndexAction';
   }
}

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

 代碼如下 複製代碼

class IndexAcion extends Action {
   public function __construct(){
       parent::__construct();
       echo 'hello IndexAction';
   }
}
   
這樣就可以將兩句話同時輸出
當然還有一種辦法就是在父類中調用子類的方法

class Action {
   public function __construct(){
       if(method_exists($this,'hello')){
           $this->hello();
       }
       echo 'hello Action';
   }
}   

class IndexAcion extends Action {
   public function hello(){
       echo 'hello IndexAction';
   }
}

   
這樣也可以將兩句話同時輸出
而這裏子類中的方法hello()就類似於ThinkPHP中_initialize()
所以,ThinkPHP中的_initialize()的出現只是方便程序員在寫子類的時候避免頻繁的使用parent::__construct()
同時正確的調用框架內父類的構造函數,所以,我們在ThnikPHP中初始化子類的時候要用_initialize(),而不用__construct(),
當然你也可以通過修改框架將_initialize()函數修改爲你喜歡的函數

原文章地址:http://www.111cn.net/phper/thinkPhp/60041.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章