恕我直言,感谢@jammin评论,这个问题值得PHP 5.6+的答案。
从PHP 5.6开始,您可以为常量定义静态标量表达式:
class Foo {
const BAR = "baz";
const HAZ = self::BAR . " boo\n";
}
尽管这不是问题的一部分,但应该意识到实施的局限性。 以下内容不起作用,尽管它是静态内容(但可以在运行时进行操作):
class Foo {
public static $bar = "baz";
const HAZ = self::$bar . " boo\n";
}
// PHP Parse error: syntax error, unexpected '$bar' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS)
class Foo {
public static function bar () { return "baz";}
const HAZ = self::bar() . " boo\n";
}
// PHP Parse error: syntax error, unexpected '(', expecting ',' or ';'
有关更多信息,请查看:[https://wiki.php.net/rfc/const_scalar_exprs]和[http://php.net/manual/zh/language.oop5.constants.php]