PHP Autoloading Classes


Introduction

In order to use class defined in another PHP script, we can incorporate it with include or require statements. However, PHP's autoloading feature doesn't 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 laast chance to load class/interface before emitting error.

Syntax

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

The class will be loaded from its corresponding .php file when it comes in use for first time

Autoloading example

This example shows how a Class is registered for autoloading

Example

<?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

This will produce following result. −

objects of test1 and test2 class created successfully

However, if corresponding .php file having clas definition is not found, following error will be displayed.

Warning: include(): Failed opening 'test10.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 4
PHP Fatal error: Uncaught Error: Class 'test10' not found

Autoloading with exception handling

Example

 Live Demo

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

Output

This will produce following result. −

Unable to load test1.

Updated on: 18-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements