Open In App

How to load classes in PHP ?

Last Updated : 31 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

PHP load classes are used for declaring its object etc. in object oriented applications. PHP parser loads it automatically, if it is registered with spl_autoload_register() function. PHP parser gets the least chance to load class/interface before emitting an 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 into use for the first time.

Autoloading

Example:

PHP




<?php
    spl_autoload_register(function ($class_name) {
        include $class_name . '.php';
    });
    $obj = new mytest1();
    $obj2 = new mytest2();
    echo "Objects of mytest1 and mytest2 "
        + "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.

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:

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