In accordance with the concepts I deployed in the previous section, it’s perfectly feasible to implement a simple workaround that provides the handy “__autoload()” function with the ability to throw an exception when one source class can’t be loaded onto a given PHP 5 application. This rather tricky solution consists of creating the troubling class via an “eval()” command, and then explicitly throwing an exception. Logically this concept will be better grasped if you take a close look at the following example. Here it is: // include required classes (the magic '__autoload()' function now throws an exception when some of the required classes are not found) function __autoload($className){ if(!file_exists($className.'.php')){ eval("class $className {}"); throw new Exception('Class not found'); } require_once $className.'.php'; } try{ // 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(); exit(); } As shown above, the “__autoload()” magic function has been implemented by using the workaround that I mentioned before. As you can see, the function first check for the existence of the files that contain the corresponding source classes, and if this process fails for some reason, it tries to create the problematic class using the “eval()” function. Finally, the function throws an explicit exception, in this way implementing a basic error handling mechanism. Nothing too complex, right? Besides, if you first remove the pertinent “mysql.php” file and test the prior example on your own web server, you’ll get an error similar to the one shown below: Fatal error: Function __autoload(MySQL) threw an exception of type 'Exception' in path/to/file Indeed, this is an advance with reference to the raw fatal error that you saw earlier. As you can see, the “__autoload()” function now is capable of launching an exception, although it still won’t be caught by a “try-catch()” block. However, that’s all the code samples that I’m going to show you for the moment. I recommend that you test all of the examples developed in this tutorial to see how they react when a source class can’t be loaded as expected. It’s an instructive experience, trust me. Final thoughts In this second installment of the series you hopefully learned how to implement a simple workaround within the handy “__autoload()” magic function to incorporate into it the capacity to throw exceptions when a specific source class is not included. Nonetheless, this quick and dirty exception mechanism isn’t completely functional yet, since a conventional “try-catch()” block won’t be able to intercept these exceptions. However, this issue will be fixed in the next part of the series, so I hope to see you there!
blog comments powered by Disqus |
|
|
|
|
|
|
|