Convert CamelCase to under_score_case in php __autoload()

天大地大妈咪最大 提交于 2019-12-03 03:10:06

问题


PHP manual suggests to autoload classes like

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

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?


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/1589468/convert-camelcase-to-under-score-case-in-php-autoload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!