I currently have the following __get/__set methods in the PHP class example:
class example{
/*Member variables*/
protected $a;
protected $b = array();
public function __get($name){
return $this->$name;
}
public function __set($name, $value){
$this->$name = $value;
}
}
However, in addition to setting standard protected variables, I would also like to be able to set protected arrays within the class. I've looked through some other questions and found general suggestions as to how to simple set variables using the __get/__set methods, but nothing that would allow one to use these magic methods to set BOTH arrays and nonarrays, i.e. in the following manner:
$fun = new $example();
$fun->a = 'yay';
$fun->b['coolio'] = 'yay2';
Simple, define __get()
like so:
public function &__get($name)
{
return $this->$name;
}
// ...
$fun = new example();
$fun->a = 'yay';
$fun->b['coolio'] = 'yay2';
var_dump($fun);
Output:
object(example)#1 (2) {
["a":protected]=>
string(3) "yay"
["b":protected]=>
array(1) {
["coolio"]=>
string(4) "yay2"
}
}
Do take necessary care when you're dealing with references, it's easy to mess up and introduce hard to track bugs.