分析ThinkPHP中__initialize()和类的构造函数__construct()用法
2022-11-24 11:02:51
168
{{single.collect_count}}

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本文实例分析了ThinkPHP中的__initialize()和类的构造函数__construct()。分享给大家供大家参考。具体分析如下:

thinkphp中的__construct是不可以随便用的,因为你的模块类继承上级类,上级类有定义好的;

相关学习推荐:thinkphp

1、__initialize()不是php类中的函数,php类的构造函数只有__construct().

2、类的初始化:子类如果有自己的构造函数(__construct()),则调用自己的进行初始化,如果没有,则调用父类的构造函数进行自己的初始化。

3、当子类和父类都有__construct()函数的时候,如果要在初始化子类的时候同时调用父类的__constrcut(),则可以在子类中使用parent::__construct().

如果我们写两个类,如下:

代码如下:

class Action{public function __construct(){echo 'hello Action';}}class IndexAction extends Action{public function __construct(){echo 'hello IndexAction';}}$test = new IndexAction;//output --- hello IndexAction
登录后复制

很明显初始化子类IndexAction的时候会调用自己的构造器,所以输出是'hello IndexAction',但是将子类修改为:

代码如下:

class IndexAction extends Action{public function __initialize(){echo 'hello IndexAction';}}
登录后复制

那么输出的是'hello Action',因为子类IndexAction没有自己的构造器,如果我想在初始化子类的时候,同时调用父类的构造器呢?

代码如下:

class IndexAction extends Action{public function __construct(){parent::__construct();echo 'hello IndexAction';} }
登录后复制

这样就可以将两句话同时输出,当然还有一种办法就是在父类中调用子类的方法.

代码如下:

class Action{public function __construct(){if(method_exists($this,'hello')){$this -> hello();}echo 'hello Action';}}class IndexAction extends Action{public function hello(){echo 'hello IndexAction';}}
登录后复制

这样也可以将两句话同时输出,而这里子类中的方法hello()就类似于ThinkPHP中__initialize()。

所以,ThinkPHP中的__initialize()的出现只是方便程序员在写子类的时候避免频繁的使用parent::__construct(),同时正确的调用框架内父类的构造器,所以,我们在ThnikPHP中初始化子类的时候要用__initialize(),而不用__construct(),当然你也可以通过修改框架将__initialize()函数修改为你喜欢的函数名.

相关推荐:编程视频课程

以上就是分析ThinkPHP中__initialize()和类的构造函数__construct()用法的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}