[英]PHP - Using a constant's value to reference a data member
I am trying to access one class object's data member by using a constant. 我试图通过使用常量来访问一个类对象的数据成员。 I was wondering if this is possible with a syntax similar to what I am using?
我想知道这是否可能使用类似于我正在使用的语法?
When I attempt to do this in the following script I get this error: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 当我尝试在以下脚本中执行此操作时,我收到此错误: 解析错误:语法错误,意外T_PAAMAYIM_NEKUDOTAYIM
class Certificate {
const BALANCE = 'cert_balance';
public function __construct() {}
}
class Ticket {
public $cert_balance = null;
public function __construct()
{
$this->cert_balance = 'not a chance';
echo $this->cert_balance."<br />";
}
}
$cert = new Certificate();
$ticket = new Ticket();
// This next code line should be equal to: $ticket->cert_balance = 'nice';
$ticket->$cert::BALANCE = 'nice!';
You need to disambiguate the expression with braces. 您需要使用大括号消除表达式的歧义。 Also, prior to PHP 5.3, you need to refer to the constant via the class name, like this:
此外,在PHP 5.3之前,您需要通过类名引用常量,如下所示:
$ticket->{Certificate::BALANCE} = 'nice!';
The PHP manual section on class constants says this 关于类常量的PHP手册部分说明了这一点
As of PHP 5.3.0, it's possible to reference the class using a variable
从PHP 5.3.0开始,可以使用变量引用该类
So in PHP 5.3.0 and higher, this will work: 所以在PHP 5.3.0及更高版本中,这将起作用:
$ticket->{$cert::BALANCE} = 'nice!';
Do: 做:
$ticket->{$cert::BALANCE} = 'nice';
So the parser knows it has to process $cert::BALANCE
first. 所以解析器知道它必须首先处理
$cert::BALANCE
。 It seems you need PHP 5.3 for this to work. 看来你需要PHP 5.3才能工作。 Otherwise, use the classname instead of
$cert
. 否则,请使用classname而不是
$cert
。
The point is that you have to put it into {}
. 关键是你必须把它放进
{}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.