HomePHP Displaying Meaningful Error Messages when Auto Loading Classes in PHP 5
Displaying Meaningful Error Messages when Auto Loading Classes in PHP 5
If you’re a PHP developer who wants to learn how to load automatically into client code all of the source classes required by your object-oriented applications, keep reading. In this series of articles, you’ll learn how to implement the magic “__autoload()” function that comes integrated with PHP 5. With this function, you'll be able to build scripts that can include automatically all of the classes needed by a given application, without using multiple “require()/require_once()” PHP statements.
All right, now that I introduced you to the primary goal of this series of educational tutorials, I think it's time to recapitulate the themes covered in the preceding article. We'll refresh some key concepts concerning the correct use of the “__autoload()” magic function in the context of a determined object-based application.
As you’ll possibly remember, in that particular article I showed you how to improve the signature of the helpful “__autoload()” PHP 5 function to provide it with the capacity to throw an exception when a specific source class can’t be included into client code for whatever reason.
In addition to adding this important feature to the function, I demonstrated how to introduce some “tweaks” into the signature of this function, with the objective of triggering exceptions that could be correctly intercepted within a conventional “try-catch()” block. In this way we would implement a powerful mechanism for loading automatically all of the classes required by a certain PHP 5-driven application, which also takes advantage of the built-in exception system offered natively by PHP 5. As you can see, in this case the best of both worlds is integrated seamlessly in the same magic function.
Of course, if you reread the previous sentence, you might think that it simply isn’t possible to introduce more modifications to the “__autoload()” function anymore, which would mean that the topic wouldn’t bear any further analysis. Not so fast! Actually, it’s perfectly feasible to improve the way that the “__autoload()” function works even more. In its current incarnation it only is capable of displaying exception messages that aren’t very descriptive, such as “Class not found” or something similar.
Indeed, it’s necessary to modify the logic of this function so it can throw exceptions that can be much more explicit and indicative of what’s going wrong when a particular source class can’t be included properly into client code. Thus, in this last article of the series I’m going to introduce some additional modifications to the current signature of the “__autoload()” function to make it throw exceptions that display more useful error messages.
As you may guess, to learn how these improvements will be achieved, you’ll have to start reading this tutorial, so don’t waste more time; begin now!