Open In App

What is autoloading classes in PHP ?

Last Updated : 14 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In order to use a class defined in another PHP script, we can incorporate it with include or require statements. However, PHP’s autoloading feature does not need such explicit inclusion. Instead, when a class is used (for declaring its object etc.) PHP parser loads it automatically, if it is registered with spl_autoload_register() function. Any number of classes can thus be registered. This way PHP parser gets a last chance to load the class/interface before emitting an error.

Syntax:

PHP




spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});


Note: The class will be loaded from its corresponding “.php” file when it comes into use for the first time.

Autoloading:

Example 1: This example shows how a class is registered for autoloading.

PHP




<?php
    spl_autoload_register(function ($class_name) {
       include $class_name . '.php';
    });
    $obj = new test1();
    $obj2 = new test2();
    echo "objects of test1 and test2 class created successfully";
?>


Output:

objects of test1 and test2 class created successfully

Note: If the corresponding “.php” file having class definition is not found, the following error will be displayed.

Output:

Warning: include(test1.php): failed to open stream:

 No such file or directory in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 3

Warning: include(): Failed opening ‘test1.php’ for inclusion (include_path=’.:/usr/local/lib/php’) 

in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 3

Fatal error: Uncaught Error: Class ‘test1’ not found in

 /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php:5

Stack trace:

#0 {main}

  thrown in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 5

Autoloading with exception handling

Example 2:

PHP




<?php
    spl_autoload_register(function($className) {
       $file = $className . '.php';
       if (file_exists($file)) {
          echo "$file included\n";
          include $file;
       
      else {
          throw new Exception("Unable to load $className.");
       }
    });
    try {
       $obj1 = new test1();
       $obj2 = new test10();
    
    catch (Exception $e) {
       echo $e->getMessage(), "\n";
    }
?>


Output: 

Unable to load test1.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads