Convert CamelCase to under_score_case in php __autoload()

后端 未结 2 1821
[愿得一人]
[愿得一人] 2021-01-30 22:30

PHP manual suggests to autoload classes like

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

and this a

2条回答
  •  别跟我提以往
    2021-01-30 22:40

    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.

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

提交回复
热议问题