Konwertuj wielkość liter CamelCase na wielkość małych liter w PHP autoload()

Instrukcja PHP sugeruje do autoload klasy jak

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

I to podejście działa dobrze, aby załadować klasę FooClass zapisaną w pliku my_dir/FooClass.php Jak

class FooClass{
  //some implementation
}

Pytanie

Jak mogę umożliwić korzystanie z funkcji _autoload() i dostęp do FooClass zapisanych w pliku my_dir/foo_class.php?

Author: Trix, 2009-10-19

2 answers

Możesz przekonwertować nazwę klasy w ten sposób...

function __autoload($class_name){
    $name = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $class_name));
    require_once("some_dir/".$name.".php");
}
 68
Author: Rik Heywood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-19 15:54:40

Nie jest to testowane, ale używałem wcześniej czegoś podobnego do konwersji nazwy klasy. Mogę dodać, że moja funkcja działa również w O (n) i nie polega na powolnym 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;
 2
Author: Corey Ballou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-19 16:02:48