6

init() method :

public function init()
{
}

__construct() method:

public function __construct()
{
}

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

Brett
  • 16,869
  • 50
  • 138
  • 258
Hoang NK
  • 461
  • 2
  • 7
  • 18

1 Answers1

11

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.

Bashir ahmad
  • 195
  • 2
  • 12
arogachev
  • 31,868
  • 6
  • 105
  • 113