开发者

PHP - Using a constant's value to reference a data member

开发者 https://www.devze.com 2023-01-10 15:12 出处:网络
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?

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

class Certificate {
    const BALANCE = 'cert_balance';

    public function __construct() {}

}

class Ticket {
    public $cert_balance = null;

    public function开发者_JAVA百科 __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:

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

The PHP manual section on class constants says this

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

So in PHP 5.3.0 and higher, this will work:

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


Do:

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

So the parser knows it has to process $cert::BALANCE first. It seems you need PHP 5.3 for this to work. Otherwise, use the classname instead of $cert.

The point is that you have to put it into {}.

0

精彩评论

暂无评论...
验证码 换一张
取 消