1 回答

TA贡献1777条经验 获得超3个赞
我们通常不将require_once()用于自动加载器,因为该文件可能根本不存在。
在您的情况下,只需更改为include_once()即可修复它:
初始化文件
spl_autoload_register(function($class){
if (file_exists("_classes/xs/" . $class . ".php")) {
include_once "_classes/xs/" . $class . ".php";
}
});
边注:
我最初使用@符号来抑制错误而不是file_exists检查,因为我认为它会更高效。但令我惊讶的是,file_exists调用版本实际上运行起来要快得多。
<?php
$scale = 1000000;
function benchmark(callable $fn, $scale = 100) {
$start = microtime(1);
for ($i=0; $i<$scale; $i++) {
$fn();
}
return microtime(1) - $start;
}
$time = benchmark(function () {
$file = './no-such-file.php';
if (file_exists($file)) {
include_once $file;
}
}, $scale);
printf("file_exists: %0.6fs\n", $time);
$time = benchmark(function () {
$file = './no-such-file.php';
@include_once $file;
}, $scale);
printf("@include_once: %0.6fs\n", $time);
结果(在 PHP 7.2 上):
file_exists: 1.067368s
@include_once: 8.830794s
- 1 回答
- 0 关注
- 188 浏览
添加回答
举报