In the section you just read, I defined a class called “User.” Admittedly, it doesn’t perform any particularly useful tasks, but it's handy for demonstrating how it can be loaded in the background by the “__autoload()” function. To accomplish this however, it’s necessary to give this function a concrete implementation, which will be very easy to understand. Take a look at the following example, which shows how to turn the “__autoload()” function into a more useful piece of code: function __autoload($class) { $file = $class . '.php'; if(!file_exists($file)) { eval("class $class {}"); throw new Exception('Class ' . $class . ' not found.'); } require_once($file); } There you have it. As you can see, all that I did before was define the “__autoload()” function so it can load in the background the file corresponding to a class whose signature hasn’t been found by the PHP interpreter. If the referenced class isn’t found, then an exception will be thrown, and eventually it will be caught either by a “catch()” block or by a custom exception handler. Logically, in the last instance a “require_once()” function is called within “__autoload(),” but it must be coded only once. Otherwise, in a typical scenario, one of these should have been coded per each requested file. Now that you've surely grasped the underlying logic of the previous “__autoload()” function, and assuming that the following script and the file that contains the “User” class resides in the same location on the file system, loading the class in the background would be as simple as this: // create instance of User class $user = new User(); // display user data echo $user; Short to write and read, isn’t it? In this case the script creates a new instance of the “User” class and displays the values assigned to its properties. This happens with only one single class. However, where the “__autoload()” function really shines is when it comes to including multiple classes within the same script, since it lets you get rid of the annoyance of this process. And with this final example, I’m finishing this round up of the most important magic functions that come included with PHP 5. If you haven’t used them yet when developing your own web application, I encourage you to give them a try, particularly for overloading properties and methods in a straightforward –- yet careful -- way. You won’t be disappointed, trust me! Final thoughtsNothing lasts forever, and this series isn’t an exception. Nonetheless, in the end I hope the experience has been instructive. In this round up you learned how to implement and use the most relevant magic functions provided by PHP 5. As with other features of the language, don’t abuse these functions, particularly when overloading methods and properties of a class. This can lead to making your code less readable and harder to maintain for other developers. Don’t miss the next PHP development tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|