如果我使用“点”在PHP类中的变量中赋值,则失败。
例如:
class bla { public $a = 'a' . 'b'; }我应该如何处理这个问题呢?
If I use a "dot" to assign a value in a variable in a PHP class, it fails.
For example:
class bla { public $a = 'a' . 'b'; }How should I approach this otherwise?
最满意答案
您只能在构造函数中执行此操作,因为必须使用常量表达式在声明上初始化类变量/属性。 从手册 :
这个声明可能包括一个初始化,但是这个初始化必须是一个常量值 - 也就是说,它必须能够在编译时进行评估,并且不能依赖运行时信息来进行评估。
这意味着你不能使用任何操作符或函数调用。
class bla { public $a; public function __construct() { $this->a = 'a' . 'b'; } }You can only do that in the constructor, as class variables/properties must be initialized on declaration with constant expressions. From the manual:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
This means you can't use any operators or function calls.
class bla { public $a; public function __construct() { $this->a = 'a' . 'b'; } }更多推荐
发布评论