Home arrow PHP arrow Page 4 - Improving Exception Throwing when Auto Loading Classes in PHP 5

The Improved Source Code - 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.

  1. Improving Exception Throwing when Auto Loading Classes in PHP 5
  2. One Step Backward
  3. Improving the Definition
  4. The Improved Source Code
By: Alejandro Gervasio
Rating: starstarstarstarstar / 6
December 18, 2007

print this article



Putting all the pieces together: listing the improved source code of the sample database-driven application

As I explained in the previous section, below I've included the definitions of all the source files that make up the sample database-driven application you learned in the beginning of this article. This time they include the modified version of the  “__autoload()” function.

Here are the files:

(definition of mysql.php file)

class MySQL{

private $host;

private $user;

private $password;

private $database;

private $connId;

// constructor

function __construct($options=array()){


throw new Exception('Connection options must be an array');


foreach($options as $option=>$value){


throw new Exception('Connection parameter cannot be empty');






// private 'connectDb()' method

private function connectDb(){


throw new Exception('Error connecting to MySQL');



throw new Exception('Error selecting database');



// public 'query()' method

public function query($sql){


throw new Exception('Error running query '.$sql.' '.mysql_error());


return new Result($this,$result);



(definition of result.php file)

class Result{

private $mysql;

private $result;

// constructor

public function __construct($mysql,$result){




// public 'fetch()' method

public function fetch(){

return mysql_fetch_array($this->result,MYSQL_ASSOC);


// public 'count()' method

public function count(){


throw new Exception('Error counting rows');


return $rows;


// public 'get_insertId()' method

public function getInsertId(){


throw new Exception('Error getting insert ID');


return $insId;


// public 'seek()' method

public function seek($row){


throw new Exception('Invalid row parameter');



throw new Exception('Error seeking row');


return $row;


// public 'getAffectedRows()' method

public function getAffectedRows(){


throw new Exception('Error counting affected rows');


return $rows;



(definition of autoload_example.php file)


function __autoload($className){


return eval("class {$className}{public function __construct(){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();



Now, having listed all of the source files that comprise the previous database-driven application, suppose that for some reason the file containing the definition of the prior “MySQL” class is simply not available. Based on this situation, when the above “autoload_sample.php” file is parsed by the PHP 5 interpreter, the “__autoload()” magic function will trigger an exception, which will then be caught by the corresponding “catch()” statement and the following error message will be displayed on the browser:

Class not found!

Pretty good, right? At this stage I've shown you how to define the “__autoload()” function in order to provide it with the capacity to trigger exceptions that can be completely intercepted by a conventional “try-catch()” block.

As usual, with many of my articles about PHP development, I encourage you to tweak the code of all the examples developed in this tutorial. Doing this will give you more practice with using the handy “__autoload()” function. Start automatically loading your own PHP 5 source classes.

Final thoughts

In this third tutorial of the series I showed you how to tweak the signature of the “__autoload()” PHP 5 magic function in order to give it the capacity to throw exceptions when a particular source class can’t be included into the client code. Of course, the most notable result of improving the definition of this function is that those exceptions can be perfectly caught within a conventional “try-catch()” block, taking advantage of the exceptions mechanism natively provided by PHP 5.

In the next (and last) part of the series, I’m going to demonstrate how to make the “__autoload()” function even more efficient and elegant by improving the way it throws all eventual exceptions.

Now that you’re aware of the subject of the next article, you simply can’t miss it!

>>> 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: