Why we use PHP __autoload() magic function?

By Faruque Ahamed Mollick

__autoload in PHP is called a magic function. This function is so useful. But many of new PHP programmer may not know what this function actually does and when they should use this function.



Now I am going to tell you what is the usage of this magic function in real life.

The __autoload() magic function in PHP may be helpful to you in your project when you are working PHP object orient base work and need to create lots of class. PHP autoload will help you to minimize the amount of code.

How to get the file size in PHP?

Replace Multiple Items In String Using PHP str_replace Function

Before I tell you the real usage of the PHP autoload magic function, I want to ask you how would you like to include a number of files which contain only classes? Most probably you will do that by using the below code:

<?php
  include "class1.php";
  include "class1.php";
  include "class1.php";
  include "class1.php";
  .
  .
  .
  include "classn.php";
?>

Suppose you have hundreds of PHP files and each file contains a class. So, in this case, you have to use include hundreds of times. But there is a better solution. I am going to tell you the solution.

Using the PHP autoload function, you don’t need to include class file several times. Hre is what to do.

PHP Weather Forecast Script That Uses OpenWeatherMap API

First, put all your classes files within a particular directory. Suppose the directory is “classes”. Now you just need to create separate files for each class keeping the filename and class name same. After that, you can include it in this way that you see in the below code:

function __autoload($className) {
  include_once "classes/$className.php";
}

The above code will not include all the class files, but it is taking attempt to include the particular file that contains the class. When you will create the object of a class only then it will include the class file.

<?php
function __autoload($className) {
  include_once "inc/classes/$className.php";
}
$obj = new Class1();
?>

The above code will include the Class1.php file. But you must have a file with the name Class1.php which contains a class that is called “Class1”. Your class name and file name should be same.

Similarly, if you create an object of Class2, then it will include Class2.php file. With this way, you don’t have to use PHP include several times. Thus it helps you minimize the amount of code in your project and also doesn’t load class files unnecessary until you create an object.

PHP Class to Get Weather Data Using OpenWeatherMap API

How to create JSON formatted text in PHP

So this is the magic of PHP __autoload() function which is really so great and amazing in the project.

I hope you like this post and from the code snippets of this post, you understand the usage of the autoload function properly.

Leave a Reply

Your email address will not be published. Required fields are marked *