Convert CamelCase to under_score_case in php __autoload()

P.M picture P.M · Oct 19, 2009 · Viewed 18.3k times · Source

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?

Answer

Rik Heywood picture Rik Heywood · Oct 19, 2009

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