autoload php files code example
Example 1: autoloader php
Example #1 Autoload example
This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Example 2: autoloading classes
inside root directory create a autoloader.php file and add the following code :
------------------------------------------------------------------------------
<?php
spl_autoload_register(function($className) {
$file = $className . '.php';
if (file_exists($file)) {
include $file;
}
});
inside your usage file :
--------------------------
<?php
include 'autoload.php';
$circle = new Circle;
$square = new Square;