Autoloading allows you to load class and interface files automatically whenever you try to create an object from a none-existent class in the context of the current script file.
We recommend one PHP source file contain a class definition.But the problem is having to write a long list of needed includes at the beginning of each script (one for each class).
<?php include 'ClassName1.php'; include 'ClassName2.php'; include 'Namespace1\ClassName3.php'; include 'Namespace2\ClassName4.php';
In PHP 5, By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.
We can use the spl_autoload_register() function to register any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined.
test.php
<?php spl_autoload_register(function ($class_name) { echo $class_name; if(file_exists($class_name . '.php')) include $class_name . '.php'; }); $obj = new ClassName1(); $obj2 = new ClassName2(); $obj3 = new Namespace1\ClassName3(); $obj4 = new Namespace2\ClassName4(); ?>
Whenever you create an object from a non-existent class, PHP looks into the current folder and load the corresponding class file using the include()
function.
In the namespaces chapter, we create a project which map namespace classes with the folder structure.
but the source codes are under lib
folder:
project/ |---index.php |---autoload.php |---lib/ (or vender) |---Lau/ |---BaseLau.php (namespace lau;class BaseLau{}) |---web/ |---App.php (namespace lau\web;class App{}) |---XXSoft/ (vender name) |---Helper.php (namespace xxsoft;class Helper{})
So, we need to modify it in spl_autoload_register
;
Create a new file autoload.php
in project
directory.
autoload.php
<?php spl_autoload_register(function ($class_name) { echo $class_name; $file = __DIR__ . '\\lib\\' . $class_name . '.php'; $file = str_replace('\\', DIRECTORY_SEPARATOR, $file); if (file_exists($file)) { include $file; } });
The value of __DIR__
is the folder path where autoload.php
is in.
in the file index.php
,we can just include and use it:
<?php include 'autoload.php';
We can throws a customize exception when the class name is fail to load.
<?php spl_autoload_register(function ($class_name) { echo "Want to load $class_name.\n"; $file = $class_name . '.php'; if (file_exists($file)) { include $file; } else{ throw new Exception("Unable to load $class_name."); } }); try { $obj = new NonExistClass(); } catch (Exception $e) { echo $e->getMessage(), "\n"; } ?>