使用 spl_autoload_register() 函数实现类的自动加载
一个文件中,往往需要使用多个别的类。这种情况下,一般是必须先在文件顶部使用 require/require_once或 include_include_once 进行加载,才能实例函数。
使用 spl_auto_register() 实现自加载的执行过程输出:
Trying to loadClass1 via ClassAutoloader::loader()
Class1::__construct
Trying to loadClass2 via Class
Autoloader::loader() Class2::__construct
spl_autoload_register - Register given function as __autoload() implementation
Description
bool spl_autoload_register([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]])
Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.
If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue. This is because spl_autoload_register()
will efectively replace the engine cache for the __autoload() function by either spl_autoload() or spl_autoload_call().
If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of
them in the order they are defined. By contrast, __autoload() may only be defined once.
目录结构:
- modernphp/ClasssAutoloader.php
- modernphp/Class1.php
- mordernphp/Class2.php
ClassAutokloader.php
class ClassAutoloader
{
public function __construct() {
spl_autoload_register(array($this, 'loader'));
}
public function loader($className) {
echo "Trying to load" , $className, ' via ', __METHOD__, "()\n";
echo "<br/>";
include $className . '.php';
}
}
$autoloader = new ClassAutoloader();
$obj = new Class1();
$obj = new Class2();
Class1.php
<?php
class Class1
{
public function __construct()
{
echo __METHOD__;
echo "<br/>";
}
}
Class2.php
<?php
class Class1
{
public function __construct()
{
echo __METHOD__;
echo "<br/>";
}
}