您好,欢迎访问一九零五行业门户网

ThinkPHP中类的构造函数_construct()与_initialize()的区别

这篇文章主要介绍了thinkphp中类的构造函数_construct()与_initialize()的区别,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
前言
相信熟悉thinkphp的phper基本上都很熟悉_initialize()这个方法,我们似乎也很少去使用_construct() ,除非自己写插件,否则还真是很少用到。
今天查看代码突然看到_construct()这个php自带的构造方法,我的第一感觉是比较陌生,虽然之前学习java时经常遇到,但是很久不用基本忘记。我平时的习惯是将知识的重点写
在我那本小笔记上,但是很久不写字,曾经高中那个那种飘逸灵动的书写笔法彻底丢到异次元。再加上之前的想法,所以就来学习学习技术大牛们写写博客,这不是为了装逼,而只是让自己工作成果的点点滴滴都能不随时间流逝而消散。下面来看看详细的介绍吧。
先贴上代码(我的环境是wamp,使用了tp框架):
创建的fatheraction.class.php文件
<?phpclass fatheraction extends action{public function __construct(){echo 'father';}}?>

创建的sonaction.class.php文件
<?phpclass sonaction extends fatheraction{public function __construct(){echo 'son';}function index(){}}?>
运行子类sonaction里的index()可以看到输出的结果:
son
如果将子类改为:
<?phpclass sonaction extends fatheraction{ public function __construct(){parent::__construct();echo 'son'; }function index(){}}?>
运行结果为;
fatherson
上面的结果可以得出结论:
在执行子类的构造函数时并不会自动调用父类的构造函数,如果你要调用的话,那么要加上parent::__construct()
当我们把上述的构造方法改为thinkphp_initialize()方法时运行会发现:结果与前面的一致,若要执行父类的_initialize()方法,也需要使用这一句:parent::_initialize()
那是不是说明php自带的构造函数__construct()与thinkphp的_initialize()方法一样的呢?
先贴上两段代码:
<?phpclass fatheraction extends action{public function __construct(){echo 'father';}}?>

<?phpclass sonaction extends fatheraction{public function _initialize(){echo 'son';}function index(){}}?>
当执行子类sonaction的index方法时发现,输出的结果为:father
即子类调用了父类的构造函数,而没有调用子类的_initialize()方法
再贴上两段代码:
<?phpclass fatheraction extends action{public function __construct(){if(method_exists($this,"hello")){$this->hello();}echo 'father';}}?>
<?phpclass sonaction extends fatheraction{public function _initialize(){echo 'son';}function index(){}function hello(){echo 'hello';}}?>
执行子类sonaction的index方法,发现输入的结果为hellofather
由此可以得出结论:
当thinkphp的父类有构造函数而子类没有时,thinkphp不会去执行子类的_initialize() ;
当thinkphp的父类子类均有构造函数时,要调用父类的构造函数必须使用parent::__construct() ----------------- _initialize()同理;
当thinkphp的子类同时存在__construct构造函数和_initialize()方法,只会执行子类的__construct构造函数(这个本人亲测,上述代码没有)。
相关推荐:
thinkphp使用之上传类uploadfile的使用
以上就是thinkphp中类的构造函数_construct()与_initialize()的区别的详细内容。
其它类似信息

推荐信息