Skip to content
Advertisement

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

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

$this->{$var}

The context is with CI datamapper get rules. I can’t seem to find what this syntax actually does. What do the {‘s do in this context?

Why can’t you just use:

$this->var

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement