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 的控制器中创建构造函数方法


- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01