当我们在一个文件中需要使用许多其他文件中的类时,就需要写很多 include 或 require,非常的麻烦。而使用自动加载,只需要一个方法,就可以自动的去包含需要的类,而不用再去写很多的 include 或 require 了
spl_autoload_register(string $funcName, [$throw=true], [$prepend=false]):bool
参数:
$funcName
我们自定义的一个函数的名字
$throw
当第一个参数指定的函数无法成功注册时,是否抛出异常
$prepend
是否把函数添加到队列之首,而不是队列尾部
下面举一个例子:
funcition test($className){
$name = $className.".php";
include $name;
}
spl_autoload_register("test", true, true);
$obj = new user;
当我们使用了未包含的类时,此函数会自动将这个类的名字抛出,抛给第一个参数指定的函数,函数用形参接受,然后在函数内包含这个文件即可。