熟悉THINKPHP的phper基本上都很熟悉
__initialize()這個(gè)方法,我們似乎也很少去使用__construct()
創(chuàng)建的FatherAction.class.php文件
<?php
class FatherAction extends Action{
public function __construct(){
echo 'father';
}
}
?>
創(chuàng)建的SonAction.class.php文件
<?php
class SonAction extends FatherAction{
public function __construct(){
echo 'son';
}
public function index(){
}
}
?>
運(yùn)行子類SonAction里的index()可以看到輸出的結(jié)果:
son
如果將子類改為:
<?php
class SonAction extends FatherAction{
public function __construct(){
parent::__construct();
echo 'son';
}
public function index(){
}
}
?>
運(yùn)行結(jié)果為;
fatherson
上面的結(jié)果可以得出結(jié)論:
在執(zhí)行子類的構(gòu)造函數(shù)時(shí)并不會(huì)自動(dòng)調(diào)用父類的構(gòu)造函數(shù),如果你要調(diào)用的話,那么要加上parent::__construct()
當(dāng)我們把上述的構(gòu)造方法改為THINKPHP
__initialize()方法時(shí)運(yùn)行會(huì)發(fā)現(xiàn):結(jié)果與前面的一致,若要執(zhí)行父類的__initialize()方法,也需要使用這一句: parent::_initialize()
那是不是說明php自帶的構(gòu)造函數(shù)__construct()與THINKPHP的_initialize()方法一樣的呢?
先貼上兩段代碼:
<?php
class FatherAction extends Action{
public function __construct(){
echo 'father';
}
}
?>
<?php
class SonAction extends FatherAction{
public function _initialize(){
echo 'son';
}
public function index(){
}
}
?>
當(dāng)執(zhí)行子類SonAction的index方法時(shí)發(fā)現(xiàn),輸出的結(jié)果為:father
即子類調(diào)用了父類的構(gòu)造函數(shù),而沒有調(diào)用子類的_initialize()方法
再貼上兩段代碼:
<?php
class FatherAction extends Action{
public function __construct(){
if(method_exists($this,"hello")){
$this->hello();
}
echo 'father';
}
}
?>
<?php
class SonAction extends FatherAction{
public function _initialize(){
echo 'son';
}
public function index(){
}
public function hello(){
echo 'hello';
}
}
?>
執(zhí)行子類SonAction的index方法,發(fā)現(xiàn)輸入的結(jié)果為hellofather
由此可以得出結(jié)論:
1.當(dāng)THINKPHP的父類有構(gòu)造函數(shù)而子類沒有時(shí),THINKPHP不會(huì)去執(zhí)行子類的_initialize();
2.當(dāng)THINKPHP的父類子類均有構(gòu)造函數(shù)時(shí),要調(diào)用父類的構(gòu)造函數(shù)必須使用parent::__construct()-----------------__initialize()同理;
3.當(dāng)THINKPHP的子類同時(shí)存在__construct構(gòu)造函數(shù)和_initialize()方法,只會(huì)執(zhí)行子類的__construct構(gòu)造函數(shù),不會(huì)執(zhí)行__initialize()函數(shù)
其實(shí)__initialize()函數(shù)就相當(dāng)于一般的調(diào)用函數(shù),只有你調(diào)用他的時(shí)候才會(huì)執(zhí)行。