PHP5: Autoloading

Posted on February 2, 2011

In version 5, PHP added a “magic” function for the convenience of class loading.

Typically what we’ve done is something like this:

include 'MyClass1.php';
include 'MyClass2.php';

$obj  = new MyClass1();
$obj2 = new MyClass2();

In PHP5, you can define a function called __autoload(), which is called if your code tries to load a class or interface that hasn’t been defined yet. This way you don’t need to include a long list of includes/requires at the top of your file.

function __autoload($class_name) {
  include $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();

In this example, PHP5 will notice that “MyClass1” hasn’t been defined yet, will call __autoload(), and then return to the previous point and try executing the code again. If the class still isn’t defined, then you’ll get the standard error. As you can see, the __autoload() function takes the class name as an argument.

Autoloading will also occur when defining a class that uses an undefined class or interface:

function __autoload($name) {
  var_dump($name);
}

class Foo implements ITest {
}

/*
string(5) "ITest" 
Fatal error: Interface 'ITest' not found in ...
*/

There are related functions that let you do things like registering one or more autoload functions, manually invoking the autoload functions, and automatically search for files with the matching file extension, for more advanced uses.

I haven’t used autoloading myself, but it could cut down on clutter, especially for big projects, if you have your files organized neatly.

Leave a Reply

  1.  

    |