Search code examples
phpautoloadautoloader

How to call __autoload() in php code


I am new to php and I want to use php5's __autoload functionality in my code. I wrote below code in my index.php but I don't understand how and when I should call __autoload function.

function __autoload($class) {
    if (file_exists($class . '.php')) {
        include($class . '.php');
    } else {
        throw new Exception('Unable to load class named $class');
    }
}

I have seen this thread also but I do not have such autoloader class in my application. Do every application need a separate class in order to use autoloading? If not can I have a single function like above and complete it's task? Can anyone explain how to call above __autoload function inside my php code?


Solution

  • You don't call __autoload() yourself, PHP does when it is trying to find the implementation of a class.

    For example...

    function __autoload($className) {
         include $className . '.php';
    }
    
    $customClass = new CustomClass;
    

    ...this will call __autoload(), passing CustomClass as an argument. This (stupid for example's sake) __autoload() implementation will then attempt to include a file by tacking the php extension on the end.

    As an aside, you should use spl_autoload_register() instead. You can then have multiple implementations, useful when using multiple libraries with auto loaders.

    ...using __autoload() is discouraged and may be deprecated or removed in the future.

    Source.