init()
method :
public function init()
{
}
__construct()
method:
public function __construct()
{
}
So, what's the differentce between them, and which should be used?
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:
- the class constructor is invoked;
- object properties are initialized according to the given configuration;
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With