我一直在尝试在yii中声明一个布尔值的全局变量,并在控制器中的不同动作函数中更改其值。以下是我想要实现的一个例子。
在... / config / main.php中我添加了以下数组: ' params' =>数组('登录' =>' true',),
在... / protected / controller / testController.php中我添加了以下代码:
<?php
class ApiController extends Controller{
public $x = '';
public function actionDisplay(){
$x=Yii::app()->params['login']; //so x now has the value "true"
echo $x; //this display "true" when i run this controller on this function
}
public function actionDisplay2(){
global $x;
echo $x; //this for some reason does not contain the value true even if x is global
}
如何在不必将每个函数中的值赋给全局变量的情况下实现此目的?如果我调用第二个函数,它会抛出一个错误,即x未定义。我的计划是按照你在java中的方式使用全局变量,例如
public class Display{
public String x = " ";
public static void Display(){
x = "True"; //global variable x is assigned the String value "True"
}
public static void DisplayTwo(){
System.out.print("Value of x is: " + x); //this will print "Value of x is: True"
}
....
}
So basically, this is how i want to use the global variable in Yii framework. Any suggestions how to achieve this please?
答案 0 :(得分:4)
您可以使用类变量来实现这一点,这是一个例子:
<?php
class ApiController extends Controller
{
public $lang = 'en';
public function beforeAction($action)
{
if(Yii::app()->session->contains('lang'))
$this->lang = Yii::app()->session['lang'];
return parent::beforeAction($action);
}
public function afterAction($action,$params)
{
Yii::app()->session['lang'] = $this->lang;
return parent::afterAction($action,$params);
}
public function actionDisplay(){
echo 'In Display action';
$this->lang = 'test'
echo $this->lang;
}
public function actionDisplay2(){
echo 'In Display2 action';
echo $this->lang;
}
}
答案 1 :(得分:2)
你可以制作静态系统变量,这里是a guide
基本在config/main.php
你必须添加
...
'params' => array(
'email' => 'steve@unixwiz.net',
'someOption' => true
),
...
然后你可以像
一样使用它$email = Yii::app()->params['email'];
答案 2 :(得分:1)
您写道,您创建了变量$login = 'false'
所以'false'有一个字符串。并且它不是空字符串所以$ login == true。只需将其更改为
'params'=>array('login' => false),
更新:关于此功能,您可能应该使用静态字段创建帮助程序类:
class SomeHelper
{
//that field can be changed and used in any place
public $static $login = false;
}
答案 3 :(得分:0)
在index.php中声明全局。