Autoload your classes in PHP

Posted: April 25, 2012 in OOPS Consept, PHP
Tags: , ,

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

This is how it works in action. We will create two classes. So create Image.php file and paste this in:

<?php
  class Image {
      function __construct() {
          echo 'Class Image loaded successfully <br />';
      }
  }
?>

Now create Test.php file and paste this in:

<?php
  class Test {

      function __construct() {
          echo 'Class Test working <br />';
      }
  }
?>

Basically, we created 2 simple classes with constructors which echo some text out. Now, create a file index.php and paste this in:
<?php
  function __autoload($class_name) {
      require_once $class_name . '.php';
  }

  $a = new Test();
  $b = new Image();
?>


When you run index.php in browser, everything is working fine (assuming all 3 files are in the same folder). Maybe you don’t see a point, but imagine that you have 10 or more classes and have to write require_once as many times.

I will show you how to properly throw exception if you are using PHP 5.3 and above. Chane your index.php to look like this:

<?php
function __autoload($class_name) {
    if(file_exists($class_name . '.php')) {
        require_once($class_name . '.php');
    } else {
        throw new Exception("Unable to load $class_name.");
    }
}

try {
    $a = new Test();
    $b = new Image();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>


Now, it checks if file exists and throws a proper Exception if it doesn’t.

That’s it. A handy functionality to spare some typing.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s