PHP - using a constant value to reference a data item

I am trying to access a single data member of a class object using a constant. I was wondering if this is possible with syntax similar to what I use?

When I try 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!';
+3
source share
2 answers

You need to eliminate the expression with curly braces. In addition, before PHP 5.3 you need to access the constant through the class name, for example:

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

a section of the PHP manual on class constants talks about this

PHP 5.3.0, ,

, PHP 5.3.0 :

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

:

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

, $cert::BALANCE. , PHP 5.3 . $cert.

, {}.

+3

Source: https://habr.com/ru/post/1757906/


All Articles