Yii2 中的 init() 和 __construct() 方法有什么区别 [英] What's the difference between init() and __construct() methods in Yii2

查看:27
本文介绍了Yii2 中的 init() 和 __construct() 方法有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

init() 方法:

public function init()
{
}

__construct() 方法:

public function __construct()
{
}

那么,它们之间有什么区别,应该使用哪个?

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

推荐答案

init() 是从 yii\base\Object(和大多数对象都是从它延伸出来的).

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

来自官方文档:

除了属性特性,Object还引入了一个重要的对象初始化生命周期.特别是创建一个新的Object 或其派生类的实例将涉及以下内容生命周期顺序:

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. 调用类构造函数;
  2. 对象属性根据给定的配置进行初始化;
  3. 调用 init() 方法.

在上面,第 2 步和第 3 步都发生在类的末尾构造函数.建议您执行对象初始化在 init() 方法中,因为在那个阶段,对象配置已经申请了.

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.

推荐使用init(),你甚至可以从源代码和扩展中看到它,但在某些情况下,你可以使用__construct().有一些建议可以实现,您可以在官方文档的同一页面上找到它 这里.

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 是原生 PHP 语言功能,您可以在 本节.

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

这篇关于Yii2 中的 init() 和 __construct() 方法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆