Back to the blog
Recent Posts
-
Aug 31
A bit of icon work
-
Jun 24
Your mobile OS can't really multitask...
-
Apr 27
Thoughts on Android and the HTC Dream
-
Feb 26
Announcing Twitterscribe: archive your tweets
-
Jan 01
Adventures in PHP interfaces
-
Oct 17
How do you mockup websites?
Most Popular Posts
-
Why you should be using a framework
-
Dynamic methods in PHP
-
Rewriting URLs with Apache's mod_rewrite and PHP
-
Five easy things that make you a better web developer
About the Blog

I'm a 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.
Comments
Thanks for great stuff
