简体   繁体   中英

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

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:

$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 {} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM