PHP 自动加载器:忽略不存在的包含
我的自动加载器有问题:
public function loadClass($className) {
$file = str_replace(array('_', '\\'), '/', $className) . '.php';
include_once $file;
}
如您所见,这非常简单。我只是推断出该类的文件名并尝试包含它。但我有一个问题;尝试加载不存在的类时出现异常(因为我有一个抛出异常的错误处理程序)。这很不方便,因为当您在不存在的类上使用 class_exists() 时它也会被触发。您不希望出现异常,只希望返回“false”。
我之前通过在包含之前添加 @ 来修复此问题(抑制所有错误)。不过,这样做的一大缺点是,此包含中的任何解析器/编译器错误(致命的)都不会显示(甚至在日志中也不会显示),从而导致很难发现错误。
同时解决这两个问题的最佳方法是什么?最简单的方法是在自动加载器中包含类似的内容(伪代码):
foreach (path in the include_path) {
if (is_readable(the path + the class name)) readable = true;
}
if (!readable) return;
但我担心那里的性能。会不会很痛?
(已解决)是这样的:
public function loadClass($className) {
$file = str_replace(array('_', '\\'), '/', $className) . '.php';
$paths = explode(PATH_SEPARATOR, get_include_path());
foreach ($paths as $path) {
if (is_readable($path . '/' . $file)) {
include_once $file;
return;
}
}
}
I have a problem with my autoloader:
public function loadClass($className) {
$file = str_replace(array('_', '\\'), '/', $className) . '.php';
include_once $file;
}
As you can see, it's quite simple. I just deduce the filename of the class and try to include it. I have a problem though; I get an exception when trying to load a non-existing class (because I have an error handler which throws exceptions). This is inconvenient, because it's also fired when you use class_exists() on a non-existing class. You don't want an exception there, just a "false" returned.
I fixed this earlier by putting an @ before the include (supressing all errors). The big drawback with this, though, is that any parser/compiler errors (that are fatal) in this include won't show up (not even in the logs), resulting in a hard to find bug.
What would be the best way to solve both problems at once? The easiest way would be to include something like this in the autoloader (pseudocode):
foreach (path in the include_path) {
if (is_readable(the path + the class name)) readable = true;
}
if (!readable) return;
But I worry about the performance there. Would it hurt a lot?
(Solved) Made it like this:
public function loadClass($className) {
$file = str_replace(array('_', '\\'), '/', $className) . '.php';
$paths = explode(PATH_SEPARATOR, get_include_path());
foreach ($paths as $path) {
if (is_readable($path . '/' . $file)) {
include_once $file;
return;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个类只会调用一次,因此性能不应该成为问题。
It will only get called once per class, so performance shouldn't be a problem.
is_read 不会产生巨大的性能差异。
is_readable won't make a huge performance difference.
class_exists() 有第二个参数
autoload
,当设置为 FALSE 时,不会触发不存在的类的自动加载器。class_exists() has a second parameter
autoload
which, when set to FALSE, won't trigger the autoloader for a nonexistant class.(已解决)是这样的:
(Solved) Made it like this: