简体   繁体   English

将CamelCase转换为php __autoload()中的under_score_case

[英]Convert CamelCase to under_score_case in php __autoload()

PHP manual suggests to autoload classes like PHP手册建议自动加载类

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

and this approach works fine to load class FooClass saved in the file my_dir/FooClass.php like 并且这种方法可以很好地加载保存在my_dir/FooClass.php文件中的类FooClass

class FooClass{
  //some implementation
}

Question

How can I make it possible to use _autoload() function and access FooClass saved in the file my_dir/foo_class.php ? 如何才能使用_autoload()函数并访问文件my_dir/foo_class.php保存的FooClass

You could convert the class name like this... 你可以像这样转换类名...

function __autoload($class_name){
    $name = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $class_name));
    require_once("some_dir/".$name.".php");
}

This is untested but I have used something similar before to convert the class name. 这是未经测试的,但我之前使用了类似的东西来转换类名。 I might add that my function also runs in O(n) and doesn't rely on slow backreferencing. 我可能会补充一点,我的函数也在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM