What is autoloading classes in PHP ?
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.
Note: The class will be loaded from its corresponding “.php” file when it comes into use for the first time.
Example 1: This example shows how a class is registered for autoloading.
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(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
thrown in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 5
Autoloading with exception handling
Unable to load test1.