Home >Backend Development >PHP Tutorial >Usage of spl_autoload_register function in PHP, splautoload_PHP tutorial
Suppose we have a class file A.php, which defines a class named A:
view plaincopy to clipboardprint?
class A
{
public function __construct()
{
echo 'Got it.';
}
Then we have an index.php that needs to use this class A. The conventional writing method is
require('A.php');
$a = new A();
But one problem is that if our index.php needs to contain not just class A, but many classes, then we have to write many lines of require statements, which sometimes makes people feel uncomfortable. .
But in versions after php5, we no longer need to do this. In php5, the __autoload function is automatically called when trying to use a class that has not been defined, so we can write the __autoload function to let php automatically load the class without having to write a long list of include files.
view plaincopy to clipboardprint?
function __autoload($class)
{
$file = $class . '.php';
if (is_file($ file)) {
require_once($file);
}
}
$a = new A();
Of course, the above is just the simplest demonstration. __autoload just goes to include_path to find the class file and loads it. We can define the rules for __autoload to load classes according to our own needs.
In addition, if we don’t want to call __autoload when automatically loading, but call our own function (or class method), we can use spl_autoload_register to register our own autoload function. Its function prototype is as follows:
bool spl_autoload_register ( [callback $autoload_function] )
view plaincopy to clipboardprint?
function loader($class)
{
$file = $class . '.php';
if (is_file($ file)) {
require_once($file);
}
}
spl_autoload_register('loader');
$a = new A();
This can also run normally. At this time, when PHP is looking for a class, it does not call __autoload but calls our own defined function loader. For the same reason, the following writing method is also possible:
view plaincopy to clipboardprint?
class Loader
{
public static function loadClass($class)
{
$file = $class . '. php';
if (is_file($file)) {
require_once($file);
}
}
}
spl_autoload_register(array('Loader', 'loadClass'));
$a = new A();