Auto Loading in PHP

Objective: To learn how we can use any instance of class without including the class file.

Generally, If we want to use the instance of any class then first we need to include the class file by any of the 4 functions:

  1. include
  2. include_once
  3. require
  4. require_once

Like below,

// included all the classes
require "classes/Testing1.php";
require "classes/Testing2.php";

//now using the functionality of class
$testing1 = new Testing1;
echo $testing1->a;

$testing2 = new Testing2;
echo $testing2->a;

But if there are many classes which we want to use then we will have to include all files to be able to make the instance of the class. Suppose if there are hundreds of classes then we will have to include all and it will take lot of time and space. To overcome with this, we can use below code:

function auto_loader($class) {
$file = "classes/{$class}.php";    //path of all the classes
//this will check if file exist
if (is_file($file)) {
//finally if file exist then it will include the file
include $file;
}
}
// To register auto_loader() to call this function sequentially when a new class is declared
spl_autoload_register("auto_loader");

//now using the functionality of class
$testing1 = new Testing1;
echo $testing1->a;

$testing2 = new Testing2;
echo $testing2->a;

Using the above code, the required class will be included automatically while using the class. It will not include other classes which are not required.
File Structure:

index.php
classes/Testing1.php
classes/Testing2.php

Related Article: Namespace in PHP

Akash Roshan

Akash is a PHP developer and wants to share his knowledge through Blogs. He is currently growing in the IT industry while fulfilling his own goals.

Leave a Reply

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