Php spl_自动加载_寄存器的工作原理
我正在学习spl_自动加载_寄存器()。我知道它的用途,只是想知道如何实际使用它。我在网上搜索了一些参考资料,每一个都有自己的方法。不过,我有兴趣了解我的一本电子书中的以下脚本 这三条线在做什么,我大致可以理解,但不能理解 确切地 自动加载函数接收一个参数$class,但为什么下面的函数根本不处理它?为哪个类或项定义路径 1)Php spl_自动加载_寄存器的工作原理,php,Php,我正在学习spl_自动加载_寄存器()。我知道它的用途,只是想知道如何实际使用它。我在网上搜索了一些参考资料,每一个都有自己的方法。不过,我有兴趣了解我的一本电子书中的以下脚本 这三条线在做什么,我大致可以理解,但不能理解 确切地 自动加载函数接收一个参数$class,但为什么下面的函数根本不处理它?为哪个类或项定义路径 1) get\u include\u path() 2) 这是干什么的$flags=PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE
get\u include\u path()
2) 这是干什么的<代码>$flags=PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE代码>
$paths = explode(PATH_SEPARATOR, get_include_path());
$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
$file = strtolower(str_replace("\\", DIRECTORY_SEPARATOR, trim($class, "\\"))).".php";
剧本
function autoload($class)
{
$paths = explode(PATH_SEPARATOR, get_include_path());
$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
$file = strtolower(str_replace("\\", DIRECTORY_SEPARATOR, trim($class, "\\"))).".php";
foreach ($paths as $path)
{
$combined = $path.DIRECTORY_SEPARATOR.$file;
if (file_exists($combined))
{
include($combined);
return;
}
}
throw new Exception("{$class} not found");
}
class Autoloader
{
public static function autoload($class)
{
autoload($class);
}
}
spl_autoload_register('autoload');
spl_autoload_register(array('autoloader', 'autoload'));
// these can only be called within a class context…
// spl_autoload_register(array($this, 'autoload'));
// spl_autoload_register(__CLASS__.'::load');
使用参数“autoload”调用函数
spl\u autoload\u寄存器
。这使得函数自动加载
在找不到类时被调用
如果找不到类,则调用函数autoload
,将错误的类名作为其参数,并且该参数实际用于其第三行
$file = strtolower(str_replace("\\", DIRECTORY_SEPARATOR, trim($class, "\\"))).".php";
它用于尝试在核心函数get\u include\u path
返回的任何目录中查找与类同名的文件(failure
class=>failure.php
file)
唯一奇怪的是$flags
变量被设置为包含在str_replace
函数的参数中,实际上根本没有使用它们;但我不知道他们是否真的需要