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
The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.
PHP $ and $$ Variables. The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc. The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.
?> Difference between Both: The variable $var is used to store the value of the variable and the variable $$val is used to store the reference of the variable.
The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using the $ symbol before the $x value. These are called variable variables in PHP.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With