PHP language article

Home >> PHP language >>

  PHP spl_autoload_register

This article will provide you a detailed explanation about spl_autoload_register().

spl_autoload_register() allows several autoloaders to be registered which will be run through in turn until a match is found.

Now, imagine we have this file tree in our application:

classes/
     user.php
order/
     customer.php   
index.php

We have to load all the classes from classes and order directory, it is so easy to do it using spl_autoload_register() like below example.

File : index.php

<?php
// File : index.php

// classes_directory_autoload to load files based on class name.
function classes_directory_autoload($class_name) 
{
    $file_name = __DIR__ .'/classes/'. $class_name .".php";
	if(file_exists($file_name)){
		include_once($file_name);
	}
}

// order_directory_autoload to load files based on class name.
function order_directory_autoload($class_name) 
{
    $file_name = __DIR__ .'/order/'. $class_name .".php";
	if(file_exists($file_name)){
		include_once($file_name);
	}
}

// register multiple autoload.
spl_autoload_register('classes_directory_autoload');
spl_autoload_register('order_directory_autoload');

// Once we create the object of class, __autoload will automatically load the specified file using class name.
$user_obj = new User();
$customer_obj = new Customer();

?>

File : classes/user.php

<?php
// File : classes/user.php

class User 
{
    public function __construct() 
	{
        echo "User class construct loaded successfully!!!";
    }
}

?>

File : order/customer.php

<?php
// File : order/customer.php

class Customer
{
    public function __construct() 
	{
        echo "Customer class construct loaded successfully!!!";
    }
}

?>

Both classes 'User & Customer' object have created in index.php, once we create the object of class, autoload will automatically load the specified file from the directory using class name.

Congratulation, now you have done the setup of spl_autoload_register() in php, download the source code and try to run in your system.

How to run these files.
You need to navigate from your server and open 'index.php' file and then output will be like below.

User class construct loaded successfully!!!
Customer class construct loaded successfully!!!
  Download code

Write your comment now