Thursday, April 2, 2009

PHP and dynamic class autoloading

Object-oriented PHP applications often are structured such that each class is contained in a separate source file. The trouble with this is that as an application gets larger and larger, it becomes increasing difficult to keep track of which class files you need for a given script. Rather than requiring every single class file in your PHP scripts, the developers of PHP came up with a neat solution in the __autoload magic function. If defined, every time an undefined class is instantiated, the __autoload function gets executed with the name of the instantiated class passed as a parameter. Suppose I store all my class files in the directory php/classes/ and name them CLASS_NAME.class.php. I could then write an __autoload function as follows:
function __autoload($class_name) {
require_once $_SERVER['DOCUMENT_ROOT']."/php/classes/".$class_name . ".class.php";
}

I then simply include the __autoload function on each script rather than requiring every single class file. When an undefined class is instantiated, it gets automatically loaded in by the autoloader. The above example is fairly rudimentary; you can do a lot more with autoloading as demonstrated in this article at Generation Five. The article talks about several different options for integrating autoloading into your applications as well as all the pitfalls you might run into.

No comments:

Post a Comment