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?
You don’t call
__autoload()yourself, PHP does when it is trying to find the implementation of a class.For example…
…this will call
__autoload(), passingCustomClassas an argument. This (stupid for example’s sake)__autoload()implementation will then attempt to include a file by tacking thephpextension 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.Source.