Spl_autoload_register problem when loading the class


Spl_autoload_register problem when loading the class

So I already asked this question here earlier, but the solutions provided didn’t work for me. Here’s my setup:


Here’s my index.php

Here’s my MyClass.php

None of my echo’s display anything. Obviously my class is also not loaded. Instead I get this error.

Fatal error: Call to undefined method MyClass::test() in //index.php on line 29

Please help. I’ve been stuck on this for quite a while now and the rest of my development is suffering. I tried moving to spl_autoload_register() only because it’s the recommended way. Now the lost time is making me regret it.

Your are calling the test() function incorrectly (using static way?).

Call the function with:

$obj = new MyClass();

If you intend to use static method like MyClass::test() , declare your function in your class as:

public static function test() {

Moreover, your autoloader is over-complicated. It can be simplified as:

$class_dir = array(
    // Add more paths here ( or you can build your own $class_dir )

function class_loader($class_name) {
    global $class_dir;
    foreach ($class_dir as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once($directory . $class_name . '.php');

3rd edit:

I noticed the path you set is incorrect.

$fileName .= BASEPATH.'/'.str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

It should be:

$filename = BASEPATH .'/' . $filename . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

As said before, it can be easily debugged by echoing the value of $filename .

原文 : Hello, buddy!


免责声明:本文内容来源于Hello, buddy!,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。