PHP language article

Home >> PHP language >>

  PHP __autoload

This article will provide you a detailed explanation about __autoload, its limitation and solution.

 __autoload is generally considered obsolete. It only allows for a single autoloader. Let's me explain using an example of __autoload. Even I have never been using this function, just a simple example in order to explain it.

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

classes/
     user.php 
     customer.php   
index.php

We have to load all the classes from classes directory, it is so easy to do it using __autoload like below example.

File : index.php

<?php
// File : index.php

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

// 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 : classes/customer.php

<?php
// File : classes/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 using class name.

Congratulation , now you have done the setup of __autoload 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!!!

Limitation of  __autoload and its solution.

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's not possible using __autoload, because we can load all the files from one directory only.

Loading multiple files from multiple directory, we can use spl_autoload_register() function, read about PHP spl_autoload_register. 

  Download code

Write your comment now