Autoloading Classes and Interfaces with Object Orientated PHP

If you have ever developed an object orientated application with php 4 then you will know what an annoyance it can be including all the different class files, well with php 5 the developers have introduced a new method called __autoload().

Note: There are two underscores before the word autoload.

The autoload function is called every time we try to access a class or interface which has not yet been defined. This may be clearer with an example.

class Car extends Vehicle
{
    //code here
}

Before PHP 5 this code would cause the error: “Fatal error: Class 'Vehicle' not found”. Now if we declare an autoload function in a file shared site wide when we try to create an instance of the Car class it would call the __autoload method it would then call the __autoload() method once again when trying to extend the Vehicle class and again when we extend the Frame class. Once all the classes that are needed have been passed to the autoload method it works backwards up the call stack executing the code inside the __autoload method for each call.

Example:

Index.php

include("shared.php");
$obj = new Car();

Now create 3 files called Frame.php, Vehicle.php and Car.php and copy the following code into the specified files.

Frame.php

class Frame
{
}

Vehicle.php

class Vehicle extends Frame
{
}

Car.php

class Car extends Vehicle
{
}

The last file is the one we are including into our index file, this includes the autoload method which is doing all our file inclusion for us.

Shared.php

function __autoload($className)
{
     echo "We are requesting the " . $className . " class";

     if(file_exists($className . ".php"))
    {
        require_once($className . ".php");
        echo "The " . $className . " has been included";
    }

}

I have added some echo statements inside the __autoload() method so you can see that it is requesting all three files before any files are actually included. Any error’s that happen inside the autoload function cannot be caught and therefore are always fatal to program execution.

I hope this article saves everyone some time, it’s certainly a great feature and definitely worth implementing on any object orientated PHP web sites you may be developing.

Files Here: AutoloadingPHP

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.