0

我的自动加载器有问题:

public function loadClass($className) {
    $file = str_replace(array('_', '\\'), '/', $className) . '.php';
    include_once $file;
}

如您所见,这很简单。我只是推断出类的文件名并尝试包含它。我有一个问题;尝试加载不存在的类时出现异常(因为我有一个引发异常的错误处理程序)。这很不方便,因为当您在不存在的类上使用 class_exists() 时也会触发它。您不希望那里出现异常,只返回“假”。

我之前通过在包含之前放置一个 @ 来解决这个问题(抑制所有错误)。但是,这样做的最大缺点是,此包含中的任何解析器/编译器错误(致命的)都不会出现(甚至不会出现在日志中),从而导致难以找到错误。

同时解决这两个问题的最佳方法是什么?最简单的方法是在自动加载器(伪代码)中包含这样的内容:

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;
                    }
    }

}
4

4 回答 4

0

每个类只会调用一次,因此性能应该不是问题。

于 2009-08-24T18:40:45.027 回答
0
 public function loadClass($className) {
     $file = str_replace(array('_', '\\'), '/', $className) . '.php';
     if(is_readable($file))
       include_once $file;
 }

is_readable 不会产生巨大的性能差异。

于 2009-08-24T18:42:31.637 回答
0

class_exists() 有第二个参数autoload,当设置为 FALSE 时,不会为不存在的类触发自动加载器。

于 2009-08-24T18:44:19.857 回答
0

(已解决)是这样的:

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;
                    }
    }

}
于 2009-08-25T16:43:56.487 回答