Monday, November 19, 2007

Using PHP5’s __autoload() function.

PHP5 has brought with it a great deal of new features, primarily the addition of better object handling. One of these functions is (or “magic methods” as PHP calls them) is the __autoload() function.

Many developers like to separate their classes into separate files, such as a database class that wraps MySQL functions, and another that handles XML processing.

Example (MySQL.php)

<?php class MySQL { /* code goes here */ } ?>

To initiate this class, you would first need to include the file MySQL.php, and then create an object

<?php require_once('MySQL.php'); $objMySQL = new MySQL(); ?>

While this does not pose a problem as is, it can start to be a pain to keep a list of all class files that are needed in a script and then include each one into your page. After a while, this can begin to pose serious problems.

With the magic function __autoload(), however, that is no longer necessary. When a class is created that has not already been included into the script, __autoload() will automatically try and include it. All that is needed is the following code.

<?php function __autoload($className) { require_once($className.'.php'); } $objMySQL = new MySQL(); ?>

Now if the MySQL.php class has not yet been included, PHP will automatically search for it and try to include, thereby saving you the trouble of have to manually do it yourself.

Things To Keep In Mind

__autoload() acts as a last ditch effort to load a class before PHP fails. Two important notes from the PHP manual are:

  • Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.
  • Autoloading is not available if using PHP in CLI interactive mode.

There are two other important things to remember. One is that the value of $className which is passed to the __autoload() function is case sensitive. If your class is named MySQL and your filename is mysql.php, the function will fail. It is also important to remember to set your include path prior to calling the script, especially if you have your class files in several locations.

<?php set_include_path(get_include_path().PATH_SEPARATOR.'includes'); set_include_path(get_include_path().PATH_SEPARATOR.'includes/classes'); set_include_path(get_include_path().PATH_SEPARATOR.'includes/classes/more_classes'); function __autoload($className) { // if your class names and file names differ in case, here's where you could change it $className = strtolower($className); // try including the class file require_once($className.'php'); } ?>

This function obviously only needs to be defined once, such as in a config.php file. Afterwards, you'll never have to worry about having to manually include all of your class files again.

Further reading: http://us2.php.net/__autoload

No comments: