views:

815

answers:

2

Hey Guys, PHP manual suggests to autoload classes like

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

and this appoach works fine to load class FooClass saved in the file my_dir/FooClass.php like

class FooClass{
  //some implementation
}

here is my question: how can I make it possible to use _autoload() function and access FooClass saved in the file my_dir/foo_class.php? thanks for your help.

[Note: 1. the CamelCase and under_score notations on the files 2. the manual link is : http://www.php.net/manual/en/language.oop5.autoload.php%5D.

+10  A: 

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");
}
rikh
Would this not have issues with a class name like *myClassName*?
cballou
Thanks for the answer rikh, your magic works! @cballou, the code works in your case too. I tested it on the following class names FooClass, fooClass, myFooClass and MyFooClass.
P.M
@cballou, nope, every time there is a lower case letter followed by an upper case letter, an underscore is inserted between them. Finally, a call to strtolower is made to ensure the final name is all lower case.
rikh
A: 

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;
cballou
Frank Farmer
This is true, however I was going for optimization as two more calls to **ord()** within a loop would be slightly excessive IMO.
cballou