What's the difference between init() and __construct() methods in Yii2

与世无争的帅哥 提交于 2019-12-10 13:39:10

问题


init() method :

public function init()
{
}

__construct() method:

public function __construct()
{
}

So, what's the differentce between them, and which should be used?


回答1:


init() is the method of any object that extends from yii\base\Object (and the majority of objects extends from it).

From official docs:

Besides the property feature, Object also introduces an important object initialization life cycle. In particular, creating a new instance of Object or its derived class will involve the following life cycles sequentially:

  1. the class constructor is invoked;
  2. object properties are initialized according to the given configuration;
  3. the init() method is invoked.

In the above, both Step 2 and 3 occur at the end of the class constructor. It is recommended that you perform object initialization in the init() method because at that stage, the object configuration is already applied.

It's recommended to use init(), you can even see it from source code and the extensions, but in some cases, you can use __construct(). There are some recommendations to implement that, you can find it on the same page in official docs here.

__constuct is a native PHP language feature, you can read more info about that in PHP official docs in this section.



来源:https://stackoverflow.com/questions/31423716/whats-the-difference-between-init-and-construct-methods-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!