I have encountered the need to access/change a variable as such:
JavaScript
x
$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:
JavaScript
$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:
JavaScript
$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:
JavaScript
$a = "hello";
$b = "hi";
$val = "a";
echo $$val; // outputs "hello"
$val = "b";
echo $$val; // outputs "hi"
Working example: http://3v4l.org/n16sk