Recently I came accross something really fancy that was introduced in PHP 5. It is appearantly possible for any class to catch all functions that are called on a class. So one function would catch $obj->callOne() as well as $obj->callTwo().
So why is this a nice feature to have, well because I am a very lazy progammer and this feature allows me to magically generate getters and setters. To do this I have the following setting for each class:
So a basic class would look something similar to this:
class MyObject {
private $my_vars = array();
private $allowed_vars;
function __construct() {
$this->allowed_vars = array('var1', 'var2', 'var3');
}
function __calls($function_name, $arguments) {
$_variablename = substr($function_name, 3);
if (array_search($_variablename, $this->allowed_vars) !== FALSE) {
if (stripos($function_name, 'get') == 0 && stripos($function_name, 'get') !== FALSE) {
return $this->my_vars[$_variablename];
} else if (stripos($function_name, 'set') == 0 && stripos($function_name, 'set') !== FALSE) {
$this->my_vars[$_variablename] = $arguments[0];
}
}
else throw new Exception('Unkown function called on '. __CLASS__);
}
}
Which does exactly that which I described above. Mind you it’s just a very basic example but it shows the power of a catch all function.
Leave a Reply