php 表达式不允许作为字段默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35037368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Expression is not allowed as field default value
提问by Vasil Gerginski
I am trying to make $app
available for the whole class.
我正在努力让$app
整个班级都可以使用。
First, I get:
首先,我得到:
"Expression is not allowed as field default value"
“表达式不允许作为字段默认值”
Second, on line 5, I get:
其次,在第 5 行,我得到:
Unidentified variable $app
未识别的变量 $app
How can I achieve my goal?
我怎样才能实现我的目标?
class UserController extends XController
{
var $app = Yii::app();;
public function init()
{
$test = $app;
回答by bpoiss
You can not call a method to set a default value for a variable in PHP, not even if it is a static method. Change it to be set in the constructor:
你不能调用一个方法来为 PHP 中的变量设置默认值,即使它是一个静态方法。将其更改为在构造函数中设置:
use Yii;
class UserController extends XController
{
var $app;
function __construct() {
$this->app = = Yii::app();
}
public function init()
{
$test = $this->app;
}
}
As a sidenote, you should not use the var
keyword in PHP versions > 4, see this questionfor explanation.
作为旁注,您不应var
在 PHP 版本 > 4 中使用关键字,请参阅此问题以获取解释。