Home arrow PHP arrow Page 4 - Throwing Basic Exceptions When Auto Loading Classes in PHP 5

Developing a simple mechanism to throw exceptions - PHP

Welcome to the second part of the series that began with “Auto loading classes in PHP 5.” Comprised of four approachable tutorials, this series walks you through the key concepts you need to understand how to automatically include classes with PHP 5, without having to use the popular include functions that are provided by this powerful server-side scripting language.

  1. Throwing Basic Exceptions When Auto Loading Classes in PHP 5
  2. Two examples of the _autoload() PHP 5 function
  3. Triggering fatal errors with the _autoload() PHP 5 function
  4. Developing a simple mechanism to throw exceptions
By: Alejandro Gervasio
Rating: starstarstarstarstar / 6
December 11, 2007

print this article



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){


eval("class $className {}");

throw new Exception('Class not found');


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


echo 'Id: '.$row['id'].' First Name: '.$row['firstname'].' Last Name: '.$row
['lastname'].' Email: '.$row['email'].'<br />';



catch(Exception $e){

echo $e->getMessage();



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!

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: