I’ve found the piece of code below in several places around the web and even here on Stack Overflow, but I just can’t wrap my head around it. I know what it does, but I don’t know how it does it even with the examples. Basically it’s storing values, but I don’t know how I add values to the registry. Can someone please try to explain how this code works, both how I set and retrieve values from it?
class Registry {
private $vars = array();
public function __set($key, $val) {
$this->vars[$key] = $val;
}
public function __get($key) {
return $this->vars[$key];
}
}
It’s using PHP’s hacked on property overloading to add entries to and retrieve entries from the private
$varsarray.To add a property, you would use…
Internally, this would add a
fookey to the$varsarray with string value “foo” via the magic__setmethod.To retrieve a value…
Internally, this would retrieve the
fooentry from the$varsarray via the magic__getmethod.The
__getmethod should really be checking for non-existent entries and handle such things. The code as-is will trigger anE_NOTICEerror for an undefined index.A better version might be