Create constructor method in controller in Yii

2020-07-18 10:30发布

I have just started to learn Yii, where I have created one PostController Controller. In this controller I am having one requirement of using Sessions.

So I have created one constructor method and its code is as follows

public $session;
public function __construct() {
    $this->session = new CHttpSession;
    $this->session->open();
}

But after creating this constructor the controller was not working and gives error. And after deleting this code my controller was working perfectly. I have written this code inside constructor to not initialize the Session in each method for actionCreate and actionUpdate.

So my question is how can we create constructor in Yii?

Thanks

标签: php mysql yii
3条回答
Lonely孤独者°
2楼-- · 2020-07-18 10:35

I use init() for that, but found what people think __construct is better.

查看更多
对你真心纯属浪费
3楼-- · 2020-07-18 10:44
public function __construct()
{
      parent::__construct($this->id, $this->module);
}
查看更多
Melony?
4楼-- · 2020-07-18 10:53

You simply forgot to call parent constructor :

public function __construct()
{
  .....
  parent::__construct();
}

You could use beforeAction instead of overriding __construct.

And Sergey is right, by default Yii will start session (autoStart), you just have to use Yii::app()->session, e.g. :

Yii::app()->session['var'] = 'value';
查看更多
登录 后发表回答