In the prior segment, I explained how to implement the "__call()" functions to intercept all of the calls made to non-existent methods of the sample "User" class. In this particular case, the function will accept only requests for a "fetch()" method, which will be used for retrieving the values assigned to the class's properties. For you to understand how to accomplish this retrieval process, you'll find a short example below that shows how to use the undeclared "fetch()" method without triggering a fatal error. Here it is: // example on utilizing 'User' class with method overloading $user = new User(); $user->fname = 'Alejandro'; $user->lname = 'Gervasio'; $user->email = 'alejandro@mydomain.com';
// display user data echo 'First Name : ' . $user->fetch('fname') . ' Last Name : ' . $user->fetch('lname') . ' Email : ' . $user->fetch('email');
/* display the following First Name : Alejandro Last Name : Gervasio Email : alejandro@mydomain.com */ There you have it. Now, via the handy "__call()" magic function it's possible to overload the "fetch()" method and use it for retrieving the values given to the properties of the "User" class. Of course, you can implement the "__call()" function in the way that best suits your needs; that process will logically depend on the context in which this function will be used. Finally, feel free to edit all of the code samples shown in this tutorial, so you can acquire a more solid foundation in working with the set of magic functions included with PHP 5. Final thoughts It's hard to believe, but we've come to the end of this third part of the series. Nevertheless, the whole experience has been instructive, since you learned how to use the "__call()" magic function to implement method overloading in PHP 5. Definitely, I don't mean to dismiss the importance of other magic functions, but possibly the trio composed by the "__set()", "__get()" and "__call()" methods is one of the most powerful ones when it comes to simplifying the tasks performed by a particular class. Naturally, this simplification comes at a cost, very frequently in terms of poorer readability and code maintenance, so make sure not to abuse them when developing your own web applications. Moving forward, in the next installment of the series I'm going to continue exploring more magic functions bundled with PHP 5. That particular tutorial will be focused on discussing the "__sleep()" and "__wakeup()" functions, which are invoked automatically by the PHP engine when serializing/unserializing objects. Don't miss the upcoming part!
blog comments powered by Disqus |
|
|
|
|
|
|
|