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?
Autoloading is the process of automatically loading PHP classes without explicitly loading them with the require() , require_once() , include() , or include_once() functions. To autoload classes, you must follow two rules: Each class must be defined in a separate file. Name your class files the same as your classes.
PHP 5 introduced the magic function __autoload() which is automatically called when your code references a class or interface that hasn't been loaded yet. This provides the runtime one last chance to load the definition before PHP fails with an error.
PHP can load class files automatically on demand (No explicit require statements are needed); The file name must match the case of the terminating class name (each class in a separate file); The directory name must match the case of the namespace names; __autoload() has been DEPRECATED as of PHP 7.2.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With