PHP Tricks


One of the best tools a programmer can have is insight into his tools of the trade. PHP, for instance, offers many little features that help in this regard. One such trick is defining a function in your class called “__call”. The idea is that this method is called whenever you try call a method the class does not define, as long as what __call does is acceptable to the caller. Of course a small example is worth a thousand words…

class Foo {     // below is the definition of the __call method.
It takes 2 parameters.     // $method - the name of the method
the user has called as a string     // $args - the arguments
passed by the user to the method when calling it as an array     
function __call($method, $args) {         echo "Calling method
\"{$method}\" with ".count($args)." arguments!\n";     } } 
$foo = new Foo; $foo->bar(1, 2, 3); // call a method not explicitly
defined in class 'Foo'

The above example will output: Calling method “bar” with 3 arguments!

I have found that this technique works well in particular when generating a tree like data structure such as a DOM. You simply have use a switch based on the method name and return a new object using the $args parameter to supply arguments to the constructor. This scheme has the advantage of localizing all of the various classes into one single interface, and it keeps the user away from the details of the underlying class hierarchy and implementation.

PrintFriendly
EmailTwitterFacebookMySpaceLinkedInDeliciousGoogle BookmarksYahoo BookmarksStumbleUponAIMShare
http://blogs.citydirect.info/developing-web-apps/?p=77#comment-