Variable variables and magic functions
This bit of code sent me on a quest to understand variable variables and how they can seem confusing when used with the $this object.
<?php class SomeClass { private $email; private $password; public function __set($name, $value) { $this->$name = $value; } } Everything I thought about Class Methods told me that this should be $this->name = $value. This however will not work. The problem as i understand it is that $this->name suggests that name is a property of the object $this. The only properties of $this are $email and $password and should therefore be accessed by $this->email or $this->password. The magic method __set() is called automatically when an object is created with parameters that are inaccessible (or don't exist). In the code above, when we are coding the magic method __set(), we don't know whether we are acting on $email, $password or some other non-existent property. So how do we solve this. Well one very neat way is to use the dynamic properties of variable variables. Basically, as it is with $value where we want this to act as a kind of place holder and directly place the value of $value into the function, we also want to place the value of $name directly into the function. Therefore we make use of the variable variables concept and use $this->$name = $value instead of $this->name = $value.
Resources::
For a general explanation of variable variables:
http://uk1.php.net/manual/en/language.variables.variable.php
For a tutorial on magic methods that uses $this->$name:
http://code.tutsplus.com/tutorials/deciphering-magic-methods-in-php--net-13085












