Josh

I'm a developer in Melbourne, Australia, and co-founder of Hello Code.

Published Sun 19 August 2007

← Home

Dynamic methods in PHP

A very nifty feature of PHP 5 is the ability to create dynamic or "magical" functions. These functions do not explicitly exist per se, but are defined through the use of a __call() function. For example, if I call $obj->getSomeData() and this method is not defined, that's where __call() steps in.

I use this in my framework as a basis for getters and setters on my data objects. A data object is really just a big associative array with getters and setters exposed, which can either be magical or can be overridden. This has several advantages – hiding of the actual array variable, ease of use (as the functions are magical) and an easy way to override these functions if extra functionality is required.

The __call function takes two parameters: function name $name, and array $arguments. Let's have a look at how I use it:

function __call($method, $params) {

if (substr($method,0,3) == 'get'){

return $this->data[substr($method,3)];

} else if (substr($method,0,3) == 'set'){

$this->data[substr($method,3)] = $params[0];

} else {
return NULL;
}

}

If the prefix is 'get', return the value; if it is 'set', set the value. Easy, right?

And if you defined a function called, for example, getUsername() that returns something different, this will be given a higher priority and get called instead of your __call() function.

To top