If you have ever worked with a PHP framework you probably have noticed some features that allow you to develop code more rapidly. In this blog, I am going to address autoloading.
Traditionally, in object oriented PHP, we create a new source file for each class. If we want to create an object of a class, we have to include the php file using require_once (or using a similar function). If we do not include the source file, we will be issued a fatal error.
Fatal error: Class 'User' not found in ...
Lets say we have a User class defined as follows in a User.php file
<?php
class User {
function __construct() {
echo "Hello, World!";
}
}
?>
If we want to create a new User object we would include user.php and use the new keyword to instantiate the class.
<?php
require_once('user.php');
$user = new User();
This is method reasonable for a small number of classes. However, large frameworks can span hundreds of classes, and having to write require_once for each class becomes a huge annoyance. PHP5 introduced an autoload magic method which is automatically called if the class source file cannot be found. The __autoload function takes a single parameter – the class being instantiated. If our class name corresponds to its file name we can do something as simple as:
<?php
function __autoload($class) {
require_once($class . ".php");
}
Now, each time you instantiate a class, the autoload function will be automatically ran and it will automagically require your class. This is great, however all classes have to be in the same directory as the callee, and any decent framework uses a class hierarchy and spreads classes out into different directories. When I was writing my framework a few years ago, I stumbled upon a pretty awesome use of the autoload function. I think the idea was borrowed from the Zend framework. In a nutshell, the class names would correspond to their location on the file system. For example, the Zend framework has a class named Zend_Controller_Action_HelperBroker, and the class path Zend/Controller/Action/HelperBroker.php. What does this mean? With some additional code in our autoload function, we can convert the class name into its respective path allowing use to create a class hierarchy on our file system.
<?php
function __autoload($class) {
$file = str_replace("_", "/", $class);
require_once($file . ".php");
}
Now, with the onset of PHP5.3 and the introduction of namespaces, this method has been kind of depreciated for a more pragmatic method. Instead of naming our classes with really long names that correspond to their path, we can use a namespace instead. Thus our autoload function would look like:
<?php
function __autoload($class) {
$file = str_replace("\\", "/", $class);
require_once($file . ".php");
}
In my next blog, I will talk more about namespaces and give a better demo on how this is used.








2. January 2011
No Comments »