ThinkPHP中的__initialize()和类的构造函数__construct()
网上有很多关于__initialize()的说法和用法,总感觉不对头,所以自己测试了一下。将结果和大家分享。不对请更正。 首先,我要说的是 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
- class IndexAction extends Action{
- public function __initialize()
- {
- echo 'hello 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';
- }
- }