Using __autoload() Function


Importing classes in php is not done as conventional programming paradigm (by writing syntax on top [import package.class;] etc). Including the actual code file into the script does it but it also creates a problem of including code every time you call a class.

The __autoload() function of php gives the ability to automatically include a class file. Whenever we create a new object of any class (by writing [new ClassName()]), if called class is not already exists in the script it triggers __autoload($class) function (if there is one implemented in script) where $class is class name passed to function automatically.

Example:

In classic php project structure all classes’ files were kept in single folder name “classes” thus implementing the function as given:

 function __autoload($class){
    // __BASE_DIR  is base path to your project folder
    // e.g. E:phpprojectsmyproject

    $dir = __BASE_DIR . '/classes/';

    $file = $dir . $class . 'php';

    if(file_exists($file)){
        include($file);
    }else{
        echo('No file exists ' . $file);
    }
}