__construct()和__initialize()

1.类的初始化,一个类如果自身有构造函数,则调用自己的构造函数进行初始化,如果没有,则调用父类的构造函数进行初始化

class Action{

  public function __construct()

  {

    echo 'hello Action';

  }

}

class IndexAction extends Action{

  public function __construct()

  {

    echo 'hello IndexAction';

  }

}

$test=new IndexAction;    //输出hello IndexAction

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

如果将子类修改为:

class IndexAction extends Action

{

  public function __initialize()

  {

    echo `hello IndexAction`;

  }

}

就会输出`hello Action` 。 因为子类IndexAction没有自己的构造器,所以就会在初始化的时候调用父类的构造器

2.如果子类父类都有构造函数的时候,初始化子类调用父类的构造函数,可以在子类构造函数里使用 parent::construct();

在初始化子类的同时调用父类的构造器

class IndexAction extends Action{

  public function __construct()

  {

    parent::__construct();

    echo 'hello IndexAction';

  }

}

3.thinkPHP中的initalize() 的出现只是方便程序员在写子类进行初始化的时候避免频繁的使用parent::construct()

还有一种方法就是在父类中调用子类的方法:

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()

class Api extends Controller

{

  protected $user;

  public function __initialize()

  {

    $this->request=Request::instance();

  }

}

原文地址:https://www.cnblogs.com/ymdphp/p/10905563.html