gpt4 book ai didi

PHP - 使用常量的值来引用数据成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:04:11 25 4
gpt4 key购买 nike

我正在尝试使用常量访问一个类对象的数据成员。我想知道是否可以使用与我正在使用的语法类似的语法?

当我尝试在以下脚本中执行此操作时,出现此错误:解析错误:语法错误,意外的 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!';

最佳答案

您需要用大括号消除表达式的歧义。此外,在 PHP 5.3 之前,您需要通过类名来引用常量,如下所示:

$ticket->{Certificate::BALANCE} = 'nice!';

PHP manual section on class constants说这个

As of PHP 5.3.0, it's possible to reference the class using a variable

因此在 PHP 5.3.0 及更高版本中,这将起作用:

$ticket->{$cert::BALANCE} = 'nice!';

关于PHP - 使用常量的值来引用数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3400873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com