访问PHP类常量 [英] Accessing PHP Class Constants

查看:86
本文介绍了访问PHP类常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP手册说

像静态成员一样,不能从对象的实例访问常量值.

Like static members, constant values can not be accessed from an instance of the object.

这说明了为什么您不能这样做

which explains why you can't do this

$this->inst = new Classname();
echo $this->inst::someconstant;

但是那为什么行得通呢?

but then why does this work?

$this->inst = new Classname();
$inst = $this->inst;
echo $inst::someconstant;

推荐答案

从PHP交互式shell:

From the PHP interactive 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解析器在属性引用之后不知道如何解析双冒号.未知是否为故意.

The reason that the former syntax fails is that the PHP parser doesn't know how to resolve the double-colon after the property reference. Whether or not this is intentional is unknown.

后一种语法之所以有效,是因为它不是直接通过属性,而是通过局部变量,解析器将其视为可以使用的局部变量:

The latter syntax works because it's not going through the property directly, but through a local variable, which the parser accepts as something it can work with:

php > $inst = $b->foo;
php > echo $inst::A;
a!

(顺便说一句,匿名属性作为属性也有同样的限制.您不能直接使用parens来调用它们,必须先将它们分配给另一个变量,然后再从那里调用它们.这已在PHP中解决.主干,但我不知道他们是否还修复了双冒号语法.)

(Incidentally, this same restriction is in place for anonymous functions as properties. You can't call them directly using parens, you have to first assign them to another variable and then call them from there. This has been fixed in PHP's trunk, but I don't know if they also fixed the double colon syntax.)

这篇关于访问PHP类常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆