1

Чем отличается __construct от init() в моделях Yii2?

Вот например:

$model = new Model()

Здесь вызовется __construct и init()? Если да, то какая разница между ними?

1 ответ 1

3

qiang:

One of the reasons for init() is about life cycles of an object (or a component to be exact).

With an init() method, it is possible to configure an object after it is instantiated while before fully initialized. For example, an application component could be configured using app config. If you override its init() method, you will be sure that the configuration is applied and you can safely to check if everything is ready. Similar thing happens to a widget and other configurable components.

Even if init() is called within constructor rather than by another object, it has meaning. For example, in CApplication, there are preInit() and init(). They set up the life cycles of an application and may be overridden so that the customization only occurs at expected life cycles.

I agree with you that the method naming is very important. Here in Yii, init() method means that an object is already fully configured and some additional initialization work should be done in this method.

http://www.yiiframework.com/forum/index.php/topic/3884-init-or-contruct/

init позволяет расширить функциональность компонентов. Безопасно сконфигурировать компонент приложения, переопределив init, не опасаясь нарушить логику работы конструктора, а так же убедиться, что компонент готов к работе.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.