在Yii中的控制器中创建构造函数方法 [英] Create constructor method in controller in Yii

查看:240
本文介绍了在Yii中的控制器中创建构造函数方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Yii,在那里我创建了一个PostController控制器.在此控制器中,我有一个使用Sessions的要求.

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();
}

但是在创建此构造函数之后,控制器无法正常工作并给出错误.删除此代码后,我的控制器运行正常.我已经在构造函数中编写了此代码,以免在actionCreateactionUpdate的每个方法中都初始化Session.

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.

所以我的问题是如何在Yii中创建构造函数?

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

谢谢

推荐答案

您只是忘了调用父构造函数:

You simply forgot to call parent constructor :

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

您可以使用 beforeAction 而不是覆盖__construct.

Sergey 是正确的,默认情况下,Yii将启动会话( autoStart ),您只需要使用Yii::app()->session,例如:

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';

这篇关于在Yii中的控制器中创建构造函数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆