What is the purpose of using "{ }" keys to access the property of a class?

Asked

Viewed 40 times

4

I was doing some tests with the magic method __get PHP and discovered a different way to access class properties, which is by using keys { }, see:

return $this->{$bar};

I can also access the property in the traditional way, which would be:

return $this->bar;

And the obtained result seemed the same to me. Now see a full illustration example:

class Foo 
{
    private $bar;
    private $prop = ":(";

    public function __construct($bar)
    {
        $this->bar = $bar;
    }

    public function __get($bar)
    {
        if ($this->{$bar}) return $this->{$bar};
    }

    public function getProp()
    {
        return $this->{$prop};
    }
}

$obj = new Foo("SOpt");

echo $obj->__get('bar');

Exit:

Sopt

Note that if I use this syntax in a method get traditional getProp():

return $this->{$prop}; 

i get the following error:

<br />
<b>Notice</b>:  Undefined variable: prop in <b>[...][...]</b> on line <b>20</b><br />
<br />
<b>Fatal error</b>:  Cannot access empty property in <b>[...][...]</b> on line <b>15</b><br />

The illustration example can be executed here.

This left me with some doubts that I will address below.

Doubts

  1. What is the purpose of using the keys { } to access the class ownership?
  2. This way of accessing properties only works with methods magic or can serve other contexts?
  • 1

    Give a read here: http://php.net/manualen/language.variables.variable.php. Summarizing is used more when you want to create a name that comes from several other variables or to specify something more complex.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.