Back to the blog
Recent Posts
-
May 18
A short story about usability
-
Apr 20
Twitter as social computer
-
Apr 03
techAU troubles - techAU.tv complains, new domain is born
-
Mar 30
Announcing the launch of techAU.com.au
-
Mar 27
TechAU repurposed as Aussie tech blogger aggregator
-
Mar 20
Are aggregator sites getting a free ride?
Most Popular Posts
-
Why you should be using a framework
-
Five easy things that make you a better web developer
-
Internet Expletive
-
Where's the Android hype?
About the Blog

I'm a web designer and web application developer in Melbourne, Australia. If you find anything useful, leave me a comment, and if you need web design, development, or accessibility and usability consulting, contact me! Cheers.
Twitter: joshsharp
Dynamic methods in PHP
Sunday 19 Aug, 2007 03:05 PM
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.
