ThinkPHP中initialize()和construct()這兩個(gè)函數(shù)都可以理解為構(gòu)造函數(shù),前面一個(gè)是tp框架獨(dú)有的,后面的是php構(gòu)造函數(shù),那么這兩個(gè)有什么不同呢?
在網(wǎng)上搜索,很多答案是兩者是一樣的,ThinkPHP中initialize相當(dāng)于php的construct,這么說是錯(cuò)誤的,如果這樣,tp為什么不用construct,而要自己弄一個(gè)ThinkPHP版的initialize構(gòu)造函數(shù)呢?
相關(guān)學(xué)習(xí)推薦:thinkphp
自己試一下就知道兩者的不同了。
a.php class a{ function __construct(){ echo 'a'; } }
b.php(注意:這里構(gòu)造函數(shù)沒有調(diào)用parent::__construct();)
include 'a.php'; class b extends a{ function __construct(){ echo 'b'; } } $test=new b();
運(yùn)行結(jié)果:
b
可見,雖然b類繼承了a類,但是輸出結(jié)果證明程序只是執(zhí)行了b類的構(gòu)造函數(shù),而沒有自動(dòng)執(zhí)行父類的構(gòu)造函數(shù)。
如果b.php的構(gòu)造函數(shù)加上parent::__construct()
,就不同了。
include 'a.php'; class b extends a{ function __construct(){ parent::__construct(); echo 'b'; } } $test=new b();
那么輸出結(jié)果是:
ab
此時(shí)才執(zhí)行了父類的構(gòu)造函數(shù)。
我們再來看看thinkphp的initialize()函數(shù)。
BaseAction.class.php class BaseAction extends Action{ public function _initialize(){ echo 'baseAction'; } IndexAction.class.php class IndexAction extends BaseAction{ public function (){ echo 'indexAction'; }
運(yùn)行Index下的index方法,輸出結(jié)果:
baseActionindexAcition
可見,子類的_initialize
方法自動(dòng)調(diào)用父類的_initialize方法。而php的構(gòu)造函數(shù)construct,如果要調(diào)用父類的方法,必須在子類構(gòu)造函數(shù)顯示調(diào)用parent::__construct();
這就是ThinkPHP中initialize和construct的不同。