PHP, $this->{$var} — what does that mean?

2019-03-09 14:19发布

问题:

I have encountered the need to access/change a variable as such:

$this->{$var}

The context is with CI datamapper get rules. I cant seem to find what this syntax actually does. What do the {'s do in this context? Why not just:

$this->var

thanks!

回答1:

This is a variable variable, such that you will end up with $this->{value-of-$val}.

See: http://php.net/manual/en/language.variables.variable.php

So for example:

$this->a = "hello";
$this->b = "hi";
$this->val = "howdy";

$val = "a";
echo $this->{$val}; // outputs "hello"

$val = "b";
echo $this->{$val}; // outputs "hi"

echo $this->val; // outputs "howdy"

echo $this->{"val"}; // also outputs "howdy"

Working example: http://3v4l.org/QNds9

This of course is working within a class context. You can use variable variables in a local context just as easily like this:

$a = "hello";
$b = "hi";

$val = "a";
echo $$val; // outputs "hello"

$val = "b";
echo $$val; // outputs "hi"

Working example: http://3v4l.org/n16sk



回答2:

First of all $this->{$var} and $this->var are two very different things. The latter will request the var class variable while the other will request the name of the variable contained in the string of $var. If $var is the string 'foo' then it will request $this->foo and so on.

This is useful for dynamic programming (when you know the name of the variable only at runtime). But the classic {} notation in a string context is very powerful especially when you have weird variable names:

${'y - x'} = 'Ok';
$var = 'y - x';
echo ${$var};  

will print Ok even if the variable name y - x isn't valid because of the spaces and the - character.