Autoload class files – PHP 5

In PHP 5 you can auto load all the classes you want with a function available in PHP 5. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

The condition to use this approach is that you should have one class per file; also the file name and class name should be same.

  1. This reduces your code and efforts to include long list of class files that you need to access classes. So here are the steps to auto load the class files in PHP5:
  2. Put all the classes files in a specific directory or folder. (i.e. classes, includes etc.)
  3. function __autoload($class_name) {
    $class_path = ‘classes/’; // relative or physical path of the folder or directory containing classes
    $class_extn = ‘.php’; // class file extention .php or in some cases .class.php
    $path = $class_path.$class_name.$class_extn;
    require_once $path;

  4. Include this function in place of long list of include statements of class files.
  5. $mobj=new myclasschild();

    $assigned = $mobj;

  6. Now just initialize your class object as you usually do when including class files.
  7. Thats all

Hope this helps you,

Sachin (