As I expressed in the section that you just read, a good epilogue for this tutorial will be demonstrating how to implement a better exception handling mechanism within the auto-loading script built earlier. So, bearing this concept in mind, below I developed a whole new code sample. It shows how to throw more insightful exceptions within the “__autoload()” function when the file to be included isn’t found. Here’s the example in question:
// define a generic exception handler function function exception_handler($e) { echo $e->getMessage(); }
set_exception_handler('exception_handler'); function __autoload($class) { $file = $class . '.php'; if(!file_exists($file)){ return eval("class {$class}{public function __construct(){throw new Exception('Class {$class} not found!');}}"); } require_once($file); }
// create instance of User class $user = new User(); // display user data echo $user; As shown before, the implementation of the “__autoload()” function now allows you to throw an improved exception if the file that needs to be included by the calling script isn’t found. It's short to code and read, indeed. And with this example, I’m completing this sixth chapter of the series on building file loading applications in PHP. As usual, feel free to tweak all of the code samples shown in this tutorial, so you can practice developing this kind of web-based program. Final thoughts That’s all for the moment. Over this sixth part of the series I discussed how to build a small –- yet helpful -- file loading application in PHP 5 by taking advantage of the nifty “__autoload()” magic function, which made the whole development process a breeze. I have to say, though that I’m only scratching the surface when it comes to creating file loaders with PHP 5. The language provides yet another pair of powerful functions that are part of the Standard PHP Library, called “spl_autoload_register()” and “spl_autoload_register().” These functions can be used for building clever file loading applications very quickly. In the next article I’m going to explore these functions in depth, so now that you know what to expect from the upcoming tutorial, you won’t want to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|