Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

yii

yii2

init() method :

public function init()
{
}

__construct() method:

public function __construct()
{
}

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

like image 525
Hoang NK Avatar asked Jul 15 '15 07:07

Hoang NK


1 Answers

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.

like image 152
arogachev Avatar answered Nov 14 '22 23:11

arogachev