前言
相信熟悉THINKPHP的phper基本上都很熟悉_initialize()
這個方法,我們似乎也很少去使用_construct()
,除非自己寫插件,否則還真是很少用到。
今天查看代碼突然看到_construct()
這個php自帶的構(gòu)造方法,我的第一感覺是比較陌生,雖然之前學習java時經(jīng)常遇到,但是很久不用基本忘記。我平時的習慣是將知識的重點寫
在我那本小筆記上,但是很久不寫字,曾經(jīng)高中那個那種飄逸靈動的書寫筆法徹底丟到異次元。再加上之前的想法,所以就來學習學習技術(shù)大牛們寫寫博客,這不是為了裝逼,而只是讓自己工作成果的點點滴滴都能不隨時間流逝而消散。下面來看看詳細的介紹吧。
先貼上代碼(我的環(huán)境是wamp,使用了TP框架):
創(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'; } function index(){ } } ?>
運行子類SonAction里的index()
可以看到輸出的結(jié)果:
son
如果將子類改為:
<?php class SonAction extends FatherAction{ public function __construct(){ parent::__construct(); echo 'son'; } function index(){ } } ?>
運行結(jié)果為;
fatherson
上面的結(jié)果可以得出結(jié)論:
在執(zhí)行子類的構(gòu)造函數(shù)時并不會自動調(diào)用父類的構(gòu)造函數(shù),如果你要調(diào)用的話,那么要加上parent::__construct()
當我們把上述的構(gòu)造方法改為THINKPHP_initialize()
方法時運行會發(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'; } function index(){ } } ?>
當執(zhí)行子類SonAction的index方法時發(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'; } function index(){ } function hello(){ echo 'hello'; } } ?>
執(zhí)行子類SonAction的index方法,發(fā)現(xiàn)輸入的結(jié)果為hellofather
由此可以得出結(jié)論:
當THINKPHP的父類有構(gòu)造函數(shù)而子類沒有時,THINKPHP不會去執(zhí)行子類的_initialize()
;
當THINKPHP的父類子類均有構(gòu)造函數(shù)時,要調(diào)用父類的構(gòu)造函數(shù)必須使用parent::__construct()
----------------- _initialize()
同理;
當THINKPHP的子類同時存在__construct
構(gòu)造函數(shù)和_initialize()
方法,只會執(zhí)行子類的__construct
構(gòu)造函數(shù)(這個本人親測,上述代碼沒有)。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對的支持。