如何在PHP的类属性中使用类常量? [英] How to use a class constant into a class attribute in PHP?
问题描述
这是不起作用的代码:
class MyClass
{
const myconst = 'somevalue';
private $myvar = array( 0 => 'do something with '.self::myconst );
}
似乎类常量在编译时"不可用,而仅在运行时可用. 有人知道有什么解决方法吗? (定义将无效)
Seems that class constants are not available at "compile time", but only at runtime. Does anyone know any workaround ? (define won't work)
谢谢
推荐答案
类声明中的问题不是使用常量,而是使用表达式.
The problem in your class declaration is not that you are using a constant, but that you are using an expression.
类成员变量称为属性". (...)通过使用关键字public,protected或private之一定义,后跟普通变量声明.该声明可以包含一个初始化,但是该初始化必须是一个常量值-也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能被评估.
Class member variables are called "properties". (...) They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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 simple declaration, for example, will not compile (parse error):
class MyClass{
private $myvar = 3+2;
}
但是,如果我们更改类声明以使用简单常量,而不是使用与该常量串联的字符串,它将按预期工作.
But if we alter your class declaration to use the simple constant, rather than a string concatenated with that constant it will work as expected.
class MyClass{
const myconst = 'somevalue';
public $myvar = array( 0 => self::myconst );
}
$obj = new MyClass();
echo $obj->myvar[0];
作为解决方法,您可以在构造函数中初始化属性:
As a work-around you could initialize your properties in the constructor:
class MyClass{
const myconst = 'somevalue';
public $myvar;
public function __construct(){
$this->myvar = array( 0 => 'do something with '.self::myconst );
}
}
$obj = new MyClass();
echo $obj->myvar[0];
希望这对您有帮助,
阿林
I hope this helps you,
Alin
这篇关于如何在PHP的类属性中使用类常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!