As I explained in the introduction of this article, if an exception is thrown during the execution of the magic “__autoload()” function, it simply won’t be caught by a “try-catch()” block, as you’d normally expect with other PHP native functions. Most likely, the function in question will trigger a fatal error instead, if for whatever reason, a source class can't be included into client code. But this is only a theory, so see for yourself what happens when the file that contains the previous “Result” class is not available to be included into the sample script that you learned before: (in this example the “result.php” file is not available) function __autoload($className){ 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(); } // Fatal error: __autoload() [function.require]: Failed opening required 'Result.php' (include_path='.;include/path/) in path/to/file As you can see, the above hands-on example demonstrates in a nutshell what happens when one of the source classes (in this case, the one called “Result”) required by the previous script isn’t available to be included into client code. In simple words, the script will complain about this problem by triggering a fatal error similar to the one show before. Undoubtedly, from a programmer’s point of view a crude fatal error might not be the best option when it comes to handing a failure that happened when trying to include a specific source class. So, is there a more efficient and elegant solution to deal with this type of error when using the “__autoload()” function? Fortunately, the answer to this question is an emphatic yes! As you’ll see in the section to come, it’s possible to implement a simple workaround which will make this function throw an exception when, for whatever reason, it fails to load a determined source class. To learn how this workaround will be developed, please go ahead and read the last section of this article. We’re almost done!
blog comments powered by Disqus |
|
|
|
|
|
|
|