HomePHP Page 3 - Improving Exception Throwing when Auto Loading Classes in PHP 5
Improving the Definition - PHP
This is the third article in the series on how to auto load classes in PHP 5. This article will demonstrate how to trigger exceptions in a way that can be caught by the corresponding "catch()" block. Please keep reading to find out more.
Improving the definition of the “__autoload()” function: throwing exceptions that can be caught by a “try-catch” block
In consonance with the concepts deployed in the prior section, it’s necessary to modify the initial definition of the “__autoload()” magic function so that it can throw an exception when it fails to include a determined source class into the code. In this case, the exception should be caught by a “try-catch()” block. It's an extremely handy technique for taking advantage of the built-in exception mechanism provided by PHP 5.
So, keeping this in mind, below I listed the improved definition of the “__autoload()” function, which, at this point, is capable of triggering exceptions that can be easily caught by a “try-catch()” block.
Having said that, the modified signature of this handy function is as follows:
function __autoload($className){
if(!file_exists($className.'.php')){
return eval("class {$className}{public function __construct(){throw new Exception('Class not found!');}}");
}
require_once $className.'.php';
}
See how easy it is to change the definition of the “__autoload()” PHP 5 function to make it throw exceptions that can be correctly intercepted within a “try-catch()” structure? I guess you do! In this particular case, I implemented the function in such a way that when it fails to include a source class, it first declares this class, then an exception is triggered by the corresponding constructor, and finally, the class’ code is returned to the program’s flow.
Of course, I should say that this workaround is quite dirty and not very elegant. But you should keep in mind that I’m trying to implement a feature that isn’t supported natively by the "__autoload()” function (i.e. triggering exceptions that can be caught within a “try-catch()” block).
So far, so good. At this stage I've demonstrated how to modify the signature of the “__autoload()” function in order to add to it a decent exception support. However, if you’re anything like me, then you may want to see for yourself whether this improved incarnation of the function really works as expected.
Thus, in the last section of this tutorial I’m going to create a fully functional example that will demonstrate how the “__autoload()” function is now capable of throwing exceptions that can be intercepted within a “try-catch()” block.
To learn how this example will be developed, go ahead and read the next few lines. They’re just one click away.