Auto loading classes allows us to use classes directly in our code without including every time we need them.
PHP introduced __autoload() function which is automatically called when the code references a class which is not loaded. This allows us to tell __autoload() where to find our classes that can be automatically loaded without including them.

First we will understand the problems with traditional coding.

  1. Let us create a class named Student in a file student.php
    <?php
    class Student
    {
        var $name;
        var $age;
        var $gender;
    
        public function showInformation(){
            echo "Hi " . $this->name;
            echo "<br/>You are a " . $this->gender;
            echo "<br/>Your age is " . $this->age;
        }
    }
    
    
  2. Create one more class named Data in file data.php
    <?php
    class Data{
        public static function add($a, $b){
            echo "Sum is " . ($a+$b);
        }
    }
    
    
  3. Now we create another file test.php in which we want to work with these two classes.
    <?php
    include 'Student.php';
    include 'Data.php';
    
    $student_1 = new Student();
    $student_2 = new Student();
    
    $student_1->name = "ABC";
    $student_1->gender = "Male";
    $student_1->age = 20;
    
    $student_2->name = "XYZ";
    $student_2->gender = "Female";
    $student_2->age = 18;
    
    $student_1->showInformation();
    
    echo "<hr/>";
    
    $student_2->showInformation();
    
    echo "<hr/>";
    
    Data::add(4,5);

The problem with this approach is that we have to include files every time we want to use. This becomes complex when there are huge number of files.

Auto-loading helps in removing this multiple includes in our files. Let us create a new file autoload.php in the same directory with following code:

<?php
   function autoload($className){
   
      $path = dirname(__FILE__) . '/' . $className . '.php';
      
      if(file_exists($path))
         require $path;
   }

   spl_autoload_register('autoload');

dirname(__FILE__) gives the path of included file.
spl_autoload_register registers the provided function with autoload queue. Click here for more information.

Now remove the two includes in your test.php and just put one line:

include "autoload.php"

Run your test.php in a browser.

Great isn’t it!