Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
pabz Avatar asked Oct 03 '12 05:10

pabz


People also ask

How do you autoload in PHP?

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.

What is the function of autoload?

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.

How do you load classes in PHP?

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.


1 Answers

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.

like image 177
Mohit Mehta Avatar answered Oct 07 '22 19:10

Mohit Mehta