29

PHP手册建议自动加载类,如

function __autoload($class_name){
 require_once("some_dir/".$class_name.".php");
}

这种方法可以很好地加载FooClass保存在文件中的类,my_dir/FooClass.php例如

class FooClass{
  //some implementation
}

问题

如何才能使用保存在文件中的_autoload()功能和访问权限?FooClassmy_dir/foo_class.php

4

2 回答 2

71

你可以像这样转换类名......

function __autoload($class_name){
    $name = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $class_name));
    require_once("some_dir/".$name.".php");
}
于 2009-10-19T15:54:40.863 回答
2

这是未经测试的,但我之前使用过类似的东西来转换类名。我可能会补充一点,我的函数也在 O(n) 中运行,并且不依赖于慢速反向引用。

// lowercase first letter
$class_name[0] = strtolower($class_name[0]);

$len = strlen($class_name);
for ($i = 0; $i < $len; ++$i) {
    // see if we have an uppercase character and replace
    if (ord($class_name[$i]) > 64 && ord($class_name[$i]) < 91) {
        $class_name[$i] = '_' . strtolower($class_name[$i]);
        // increase length of class and position
        ++$len;
        ++$i;
    }
}

return $class_name;
于 2009-10-19T15:56:47.507 回答