Programming Language

The __Autoload Function In PHP

All the PHP functions that begin using a double underscore are known as PHP magic functions. In the same way, the __autoload function is also known as a magic function. This is because it possesses a double underscore in front of it.

Significance of autoload function

The __autoload function is used in PHP for simplifying programmer’s job by incorporating classes in an automatic way. The programmer doesn’t need to add a very huge number of include statements. The below example will clarify this.

include “sample/sample.Foo.php”;

include “sample/sample.AB.php”;

include “sample/sample.XZ.php”;

include “sample/sample.YZ.php”;

 

$doo = new Doo;

$cd = new CD;

$xy = new XY;

$wy = new WY;

 

In the above code, you can see that we have included each of the class files one by one. This is due to the fact that we are creating each class’s instance, so we must have each class file. Of course, here we have assumed that developers are just defining one class each source file. This is in fact a good practice while you are writing object oriented programs, although you are permitted to have several classes in one source file.

Inclusion of Class Files Simplify the __Autoload Function in PHP

Suppose if we require using 20 or 30 different classes inside one file. Here, writing out every include statement could become problematic. The PHP __autoload function helps in solving this problem because it allows PHP to automatically load the classes for us! So, instead of the above code, we can simply use the __autoload function as illustrated below:

 

function __autoload($sample_name)

{

need_once “./class/class.”.$class_name.“.php”;

}

 

$doo = new Doo;

$cd = new CD;

$xy = new XY;

$wy = new WY;

 

Working Of The __Autoload Function

Since the __autoload function is a magic function, thus the programmer does not need to call it directly. Rather, it is called by PHP behind the scenes– and this is the feature that makes it magical. So, when does the __autoload function truly get called? Here, in the above code, the __autoload function is going to be called 4 times, because PHP will not be able to recognize the Doo, CD, XY, and WY classes so PHP will surely make a call to the __autoload function every time when it does not identify a class name.

Leave a Reply