ThinkPHP中_initialize()与__construct()用法
2015-01-06 15:09
751 查看
1 _initialize()不是php类中的构造函数,php类的构造函数只有__construct().
2 类的初始化:子类如果有自己的构造函数__construct(),则调用自己的进行初始化,如果没有,
则调用父类的构造函数进行自己的初始化
3 当子类和父类都有__construct()函数的时候,如果要在初始化子类的时候同时调用父类的__constrcut(),
则可以在子类中使用parent::__construct().
如果我们写两个类,如下
很明显初始化子类IndexAction的时候会调用自己的构造函数,所以输出是'hello IndexAction'
但是将子类修改为
那么输出的是'hello Action',因为子类IndexAction没有自己的构造函数
如果我想在初始化子类的时候,同时调用父类的构造器呢?
这样也可以将两句话同时输出
而这里子类中的方法hello()就类似于ThinkPHP中_initialize()
所以,ThinkPHP中的_initialize()的出现只是方便程序员在写子类的时候避免频繁的使用parent::__construct()
同时正确的调用框架内父类的构造函数,所以,我们在ThnikPHP中初始化子类的时候要用_initialize(),而不用__construct(),
当然你也可以通过修改框架将_initialize()函数修改为你喜欢的函数
原文章地址:http://www.111cn.net/phper/thinkPhp/60041.htm
2 类的初始化:子类如果有自己的构造函数__construct(),则调用自己的进行初始化,如果没有,
则调用父类的构造函数进行自己的初始化
3 当子类和父类都有__construct()函数的时候,如果要在初始化子类的时候同时调用父类的__constrcut(),
则可以在子类中使用parent::__construct().
如果我们写两个类,如下
代码如下 | 复制代码 |
class Action { public function __construct(){ echo 'hello Action'; } } class IndexAcion extends Action { public function __construct(){ echo 'hello,IndexAction'; } } $test = new IndexAcion(); output --- hello IndexAction |
很明显初始化子类IndexAction的时候会调用自己的构造函数,所以输出是'hello IndexAction'
但是将子类修改为
代码如下 | 复制代码 |
class IndexAcion extends Action { public function _initialize(){ echo 'hello IndexAction'; } } |
那么输出的是'hello Action',因为子类IndexAction没有自己的构造函数
如果我想在初始化子类的时候,同时调用父类的构造器呢?
代码如下 | 复制代码 |
class IndexAcion 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 IndexAcion extends Action { public function hello(){ echo 'hello IndexAction'; } } |
这样也可以将两句话同时输出
而这里子类中的方法hello()就类似于ThinkPHP中_initialize()
所以,ThinkPHP中的_initialize()的出现只是方便程序员在写子类的时候避免频繁的使用parent::__construct()
同时正确的调用框架内父类的构造函数,所以,我们在ThnikPHP中初始化子类的时候要用_initialize(),而不用__construct(),
当然你也可以通过修改框架将_initialize()函数修改为你喜欢的函数
原文章地址:http://www.111cn.net/phper/thinkPhp/60041.htm
相关文章推荐
- ThinkPHP中__initialize()和类的构造函数__construct()用法分析
- ThinkPHP中__initialize()和类的构造函数__construct()用法分析
- ThinkPHP中__initialize()和类的构造函数__construct()用法分析
- ThinkPHP中initialize和construct的不同
- thinkphp 中_initialize和__construct的区别
- ThinkPHP中initialize和construct的不同
- ThinkPHP中initialize和construct的不同
- ThinkPHP中类的构造函数_construct()与_initialize()的区别详解
- ThinkPHP中initialize和construct的不同
- ThinkPHP之__construct()和__initialize()
- 浅谈ThinkPHP中initialize和construct的区别
- thinkphp 中_initialize和__construct的区别
- ThinkPHP中的__initialize()和类的构造函数__construct()
- ThinkPHP之__construct()和__initialize()
- thinkphp 中__construct与_initialize()的区别
- thinkphp篇之__construct()和__initialize()
- ThinkPHP之__construct()和__initialize()
- ThinkPHP之__construct()和__initialize()
- ThinkPHP initialize 和 construct的区别
- ThinkPHP中initialize和construct的不同