Editing live sites and the power of __autoload() in PHP 5
I have always wondered how many web developers have a development server to program on and how many just edit the PHP script their site is running on. I know that I am the second and often parts of my website will seem to fall over when I am working on them. This is where the power of the __autoload function introduced in PHP 5 can be showcased.
What is __autoload
The __autoload method is a way to load classes in PHP as they are needed. This means that programs can can control:
- Which classes are loaded
- When to load classes
- Which version of classes to load
It is called when PHP can not find a class to load and fails if __autoload can not load the requested class.
From the PHP manual:
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 which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
It goes on to give the example of:
This example attempts to load the classes >MyClass1 and MyClass2 from the files MyClass1.php and >MyClass2.php respectively.
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Editing a section of a site
I am often editing the PHP code on my site, and this means that errors may appear on parts of the site, or access to parts of the site prevented. The power of __autoload means that any errors that PHP encounters when parsing a file containing one class can be limited to whenever that class is used. The class might be only used on one page of the site, so instead of a syntax error taking down the entire site, pages only display errors when that section of the code is used.
Easy to maintain code
One of the things about PHP that used to get to me was the requirement to include so many classes separately. I have always have one PHP class in each file so 100 PHP classes means 100 files. This is a long list of paths to change. PHP code can become much more maintainable through the use of __autoload.
Speed and Performance
There is a very simple rule when it comes to loading classes: "the more you load, the longer it is going to take". As you create more and more classes, PHP will take longer parsing each one and this affects your websites speed.
Through the use of __autoload and on demand loading, the code overhead can be reduced significantly reducing the code base size with potential errors for each page and loading time decreased.