[ Team LiB ] Previous Section Next Section

Automatically Loading Include Files with ___autoload()

In a large project, code files tend to fill up with calls to include_once(). Very often, you will find that you are loading many files unnecessarily as you copy around amended source files. By the same token, you waste time adding include_once() calls to class files, only to run the script and discover that more files need including. PHP 5 provides the built-in __autoload() function, which is automatically called whenever you try to instantiate an nonexistent class. __autoload() is passed a string variable representing the class name that was not found. You can then use this string to include a source file:


<?php
function ___autoload ($class) {
  $file = "$class.inc.php";
  include_once( $file );
}
$test = new Artichoke ();
?>

In this fragment, we attempt to instantiate an object from a nonexistent Artichoke class. __autoload() is automatically called. As long as a file called artichoke.inc.php exists and contains the Artichoke class, the file will be included and the object instantiated. Remember, however, that __autoload was introduced with PHP 5.

    [ Team LiB ] Previous Section Next Section