ThinkPHP中initialize()和construct()這兩個函數都可以理解爲構造函數,前面一個是tp框架獨有的,後面的是php構造函數,那麼這兩個有什麼不同呢?
在網上搜索,很多答案是兩者是一樣的,ThinkPHP中initialize相當於php的construct,這麼說是錯誤的,如果這樣,tp爲什麼不用construct,而要自己弄一個ThinkPHP版的initialize構造函數呢?
自己試一下就知道兩者的不同了。
a.php
class a{
function __construct(){
echo 'a';
}
}
複製代碼
b.php(注意:這裏構造函數沒有調用parent::__construct();)
include 'a.php';
class b extends a{
function __construct(){
echo 'b';
}
}
$test=new b();
複製代碼
運行結果:
b
複製代碼
可見,雖然b類繼承了a類,但是輸出結果證明程序只是執行了b類的構造函數,而沒有自動執行父類的構造函數。
如果b.php的構造函數加上parent::__construct(),就不同了。
include 'a.php';
class b extends a{
function __construct(){
parent::__construct();
echo 'b';
}
}
$test=new b();
複製代碼
那麼輸出結果是:
ab
複製代碼
此時才執行了父類的構造函數。
我們再來看看thinkphp的initialize()函數。
BaseAction.class.php
class BaseAction extends Action{
public function _initialize(){
echo 'baseAction';
}
複製代碼
IndexAction.class.php
class IndexAction extends BaseAction{
public function (){
echo 'indexAction';
}
複製代碼
運行Index下的index方法,輸出結果:
baseActionindexAcition
複製代碼
可見,子類的_initialize方法自動調用父類的_initialize方法。而php的構造函數construct,如果要調用父類的方法,必須在子類構造函數顯示調用parent::__construct();
這就是ThinkPHP中initialize和construct的不同。