PHP手册说
Like static members, constant values can not be accessed from an instance of the object.
这解释了为什么你不能这样做
$this->inst = new Classname();
echo $this->inst::someconstant;
那为什么会这样呢?
$this->inst = new Classname();
$inst = $this->inst;
echo $inst::someconstant;
最佳答案
来自 PHP 交互式 shell:
php > class Foo { const A = 'a!'; }
php > class Bar { public $foo; }
php > $f = new Foo;
php > $b = new Bar;
php > $b->foo = $f;
php > echo $b->foo::A;
PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';' in php shell code on line 1
前一种语法失败的原因是 PHP 解析器不知道如何解析属性引用后的双冒号。这是否是故意的尚不得而知。
后一种语法之所以有效,是因为它不是直接通过属性,而是通过一个局部变量,解析器接受它作为它可以使用的东西:
php > $inst = $b->foo;
php > echo $inst::A;
a!
(顺便说一句,对于作为属性的匿名函数也有同样的限制。你不能使用括号直接调用它们,你必须先将它们分配给另一个变量然后从那里调用它们。这已在 PHP 中得到修复trunk,但我不知道他们是否也修复了双冒号语法。)
关于php - 访问 PHP 类常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5447541/