【发布时间】:2014-06-07 04:30:01
【问题描述】:
我一直在尝试在 yii 中声明一个布尔值的全局变量,并在控制器中的不同操作函数中更改其值。下面是我想要实现的一个示例。
在 .../config/main.php 我添加了以下数组: 'params'=>array('login' => '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?
【问题讨论】:
-
最好的办法是根本不使用全局变量。最好使用类变量 (
$this->login) 或会话变量 (Yii::app()->session['login'] = true)。 -
框架没有同时执行
actionDisplay和actionDisplay2。在正常情况下,每个请求只运行一个操作。您可以在beforeAction($action)方法中添加应该重用的代码。 -
嗨,Katchar,你能告诉我一个简短的例子吗?我如何在控制器中使用类变量来实现我想实现的目标,如上面和下面在我的 cmets 中所解释的那样?
标签: php function yii boolean global-variables