How to call __autoload() in php code How to call __autoload() in php code php php

How to call __autoload() in php code


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.


In PHP __autoload() is a magic method, means it gets called automatically when you try create an object of the class and if the PHP engine doesn't find the class in the script it'll try to call __autoload() magic method.

You can implement it as given below example:

function __autoload($ClassName){    include($ClassName.".php");}$CustomClassObj = new CustomClass();$CustomClassObj1 = new CustomClass1();$CustomClassObj2 = new CustomClass2();

It'll automatically include all the class files when creating new object.

P.S. For this to work you'll have to give class file name same as the class name.


You guys need to use require_once instead of include which will eat your memoryThe best way is:

function __autoload($class) {   $class_name = strtolower($class);   $path       = "{$class}.php";   if (file_exists($path)) {       require_once($path);   } else {       die("The file {$class}.php could not be found!");   }}