防止使用 spl_autoload_register 加载不必要的类文件

我在一个目录中有相当多的类文件_classes,我想拆分它们以防止它们都被不必要地加载。我希望它工作的方式是让目录中的所有类文件_classes/xs通过spl_autoload_register(). _classes/static然后,需要手动加载目录中的任何类文件。


我已经创建了新目录并将所有文件移动到它们的相关文件夹中,但是当我使用 时spl_autoload_register(),它也会尝试包含来自的文件,/static即使我已经指向xs.


代码

init.php:


spl_autoload_register(function($class){

    require_once "_classes/xs/" . $class . ".php";

});

example.php:


require_once "init.php";

require_once "_classes/static/Class.php";

错误

警告:require_once(_classes/xs/Class.php):打开流失败:init.php 中没有这样的文件或目录


所以所有文件xs都正确加载,但它也试图从中检索文件static(它不应该是)。


感谢所有帮助,欢呼。


德玛西亚99
浏览 189回答 1
1回答

慕森王

我们通常不将require_once()用于自动加载器,因为该文件可能根本不存在。在您的情况下,只需更改为include_once()即可修复它:初始化文件spl_autoload_register(function($class){&nbsp; &nbsp; if (file_exists("_classes/xs/" . $class . ".php")) {&nbsp; &nbsp; &nbsp; &nbsp; include_once "_classes/xs/" . $class . ".php";&nbsp; &nbsp; }});边注:我最初使用@符号来抑制错误而不是file_exists检查,因为我认为它会更高效。但令我惊讶的是,file_exists调用版本实际上运行起来要快得多。<?php$scale = 1000000;function benchmark(callable $fn, $scale = 100) {&nbsp; &nbsp; &nbsp; &nbsp; $start = microtime(1);&nbsp; &nbsp; &nbsp; &nbsp; for ($i=0; $i<$scale; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $fn();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return microtime(1) - $start;}$time = benchmark(function () {&nbsp; &nbsp; &nbsp; &nbsp; $file = './no-such-file.php';&nbsp; &nbsp; &nbsp; &nbsp; if (file_exists($file)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; include_once $file;&nbsp; &nbsp; &nbsp; &nbsp; }}, $scale);printf("file_exists:&nbsp; &nbsp;%0.6fs\n", $time);$time = benchmark(function () {&nbsp; &nbsp; &nbsp; &nbsp; $file = './no-such-file.php';&nbsp; &nbsp; &nbsp; &nbsp; @include_once $file;}, $scale);printf("@include_once: %0.6fs\n", $time);结果(在 PHP 7.2 上):file_exists:&nbsp; &nbsp;1.067368s@include_once: 8.830794s
打开App,查看更多内容
随时随地看视频慕课网APP