
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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
<?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.
- Related Articles
- PHP Anonymous classes
- PHP Accessing Global classes
- Default Autoloading in Perl
- Anonymous classes in PHP 7?
- Pseudo-classes and CSS Classes
- Pseudo-classes and all CSS Classes
- C# Nested Classes
- Bootstrap Contextual classes
- Bootstrap Helper Classes
- Python Exception Base Classes
- Storage Classes in C
- Nested Classes in C++
- Anonymous classes in C++
- C++ Stream Classes Structure
- Nested Classes in Java
