4

How can I create a constructor in a Yii2 controller? I am trying to find out what exactly is the $id $module and $config = [] in the parent::__construct arguments.

public function __construct($id, $module, $config = [])
{
    $this->id = $id;
    $this->module = $module;
    parent::__construct($config);
}

I would appreciate a working example.

2
  • 1
    I don't understand. If you want do something on start, create a init() function. Commented Aug 2, 2015 at 13:00
  • @joaner I realize in theory they are both one and the same with their functionality but how can I do it using __construct. Commented Aug 2, 2015 at 13:06

2 Answers 2

9

There shouldn't be anything wrong with

public function __construct($id, $module, $config = [])
{
    \yii\helpers\VarDumper::dump([$id, $module, $config]);
    parent::__construct($id, $module, $config);
}

if the goal is to investigate what happens there.

For production it is better to stick to overriding init method and use $this->id and $this->module there if needed. That's where the framework expects initialization code to be placed:

It is recommended that you perform object initialization in the init() method because at that stage, the object configuration is already applied.

Sign up to request clarification or add additional context in comments.

Comments

2

in yii2 you can use init function rather than constructor function

It's recommended to use init(), you can found it a lot in the extensions, but in some cases, you should use __construct(). you can find it here.

construct runs on a new instance, and then it calls the init() function which calls all the default values and functions in the class to set. so using init() is more easily and safely and do the same work as __construct() function

 public function init() {
    your code
}

3 Comments

While this answer may be correct. Code only answers are rarely helpful. Please comment your code and provide an explanation for how this code solves the problem.
thanks i add more informations about init() function what it used for and why we should use it rather than the constructor function
Vote up, because with explanation, your answer is actually helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.