Create constructor method in controller in Yii(在 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();
}
但是在创建此构造函数后,控制器无法正常工作并出现错误.删除此代码后,我的控制器运行良好.我在构造函数中编写了这段代码,以便在 actionCreate 和 actionUpdate 的每个方法中不初始化 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 的控制器中创建构造函数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Yii 的控制器中创建构造函数方法
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
