__construct()和__initialize()

ThinkPHP中的__initialize()和类的构造函数__construct()
网上有不少关于__initialize()的说法和用法,总感受不对头,因此本身测试了一下。将结果和你们分享。不对请更正。
首先,我要说的是
一、__initialize()不是php类中的函数,php类的构造函数只有__construct().
二、类的初始化:子类若是有本身的构造函数(__construct()),则调用本身的进行初始化,若是没有,则调用父类的构造函数进行本身的初始化。
三、当子类和父类都有__construct()函数的时候,若是要在初始化子类的时候同时调用父类的__constrcut(),则能够在子类中使用parent::__construct().
若是咱们写两个类,以下php

  1. class Action{
  2.     public function __construct()
  3.     {
  4.         echo 'hello Action';
  5.     }
  6.  }
  7.  class IndexAction extends Action{
  8.     public function __construct()
  9.     {
  10.         echo 'hello IndexAction';
  11.     }
  12.  }
  13. $test = new IndexAction;
  14.  //output --- hello IndexAction
复制代码

很明显初始化子类IndexAction的时候会调用本身的构造器,因此输出是'hello IndexAction'。
可是将子类修改成html

  1. class IndexAction extends Action{
  2.     public function __initialize()
  3.     {
  4.         echo 'hello IndexAction';
  5.     }
  6.  }
复制代码

那么输出的是'hello Action'。由于子类IndexAction没有本身的构造器。
若是我想在初始化子类的时候,同时调用父类的构造器呢?程序员

  1. class IndexAction extends Action{
  2.     public function __construct()
  3.     {
  4.         parent::__construct();
  5.         echo 'hello IndexAction';
  6.     }
  7.  }
复制代码

这样就能够将两句话同时输出。
固然还有一种办法就是在父类中调用子类的方法。thinkphp

  1. class Action{
  2.     public function __construct()
  3.     {
  4.         if(method_exists($this,'hello'))
  5.         {
  6.             $this -> hello();
  7.         }
  8.         echo 'hello Action';
  9.     }
  10.  }
  11.  class IndexAction extends Action{
  12.     public function hello()
  13.     {
  14.         echo 'hello IndexAction';
  15.     }
  16.  }
复制代码

这样也能够将两句话同时输出。
而,这里子类中的方法hello()就相似于ThinkPHP中__initialize()。
因此,ThinkPHP中的__initialize()的出现只是方便程序员在写子类的时候避免频繁的使用parent::__construct(),同时正确的调用框架内父类的构造器,因此,咱们在ThnikPHP中初始化子类的时候要用__initialize(),而不用__construct(),固然你也能够经过修改框架将__initialize()函数修改成你喜欢的函数名。框架

 

 

http://www.thinkphp.cn/code/367.html函数

相关文章
相关标签/搜索