Boosting up the existing capacity of the “__autoload()” magic function: displaying descriptive error messages In accordance with the concepts I explained in the previous section, it’s perfectly possible (and desirable, actually) to modify the current signature of the “__autoload()” magic function so that, whenever a given source class can’t be included into client code, it throws the corresponding exception accompanied by a meaningful error message. Given that, to implement this functionality, I’m going to make a slight change to the signature of the pertinent function, so now it looks like this: function __autoload($className){ if(!file_exists($className.'.php')){ return eval("class {$className}{public function __construct(){throw new } require_once $className.'.php'; } Not too difficult to grasp, right? As you can see, now all of the exceptions triggered by the above “__autoload()” function will indicate which source class wasn’t loaded at runtime, since the name of the troubling class is simply passed to the constructor of the built-in Exception class. To illustrate even more clearly how the “__autoload()” function works after introducing the previous modification, below I included an example that displays a “MySQL class not found” error message, when this class can’t be automatically loaded. The corresponding code sample is as follows: try{ function __autoload($className){ if(!file_exists($className.'.php')){ return eval("class {$className}{public function __construct(){throw new } require_once $className.'.php'; } // connect to MySQL $db=new MySQL(array // fetch users from database table $result=$db->query('SELECT * FROM users ORDER BY id'); // display user data while($row=$result->fetch()){ echo 'Id: '.$row['id'].' First Name: '.$row['firstname'].' Last Name: '.$row } } catch(Exception $e) { echo $e->getMessage(); } As I said before, if you test the above example on your own computer system and purposely remove the file that contains the pertinent “MySQL” class, then the “__autoload()” function will trigger an exception with the following error message: “Class MySQL not found!” Indeed, this message is much more meaningful than a raw “Class not found” text, because it gives you a clear idea of which source class couldn’t be correctly loaded by the “__autoload()” function during the execution of a given application. Okay, at this stage you hopefully learned how to tweak the signature of this handy function to display more descriptive error messages when something goes wrong. However, there are many other approaches that can be implemented to get the same results that you saw earlier. Nevertheless, in this article I’m going to show you only one more of these additional approaches, which as you’ll see in a moment, will be based on working with the so-called exceptions sub classing. Do you want to see how this technique will be developed? Click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|