I have this code below that simply load a class from a separate php file that should extends the parent class Loader

parent class

namespace Loader;

class Loader{
    public function load($name){

        $module_name = ucfirst($name);
        require_once(__DIR__.'/'.$module_name.'.php');

        return new $module_name;
    }
    public function parentFunction(){
       return get_class($this);
    }
}

$loader = new Loader;

Captcha.php

namespace Loader;

class Captcha extends Loader{
    public function callParentFunction(){
        var_dump($this->parentFunction());
    }
}

then call the captcha from Loader via test.php

require_once(__DIR__.'/Loader.php');

$loader->load('captcha')->callParentFunction();

it throws me this error:

Fatal error: Class 'Loader' not found

pointing this line

class Captcha extends Loader{

any help, suggestions?

1 Answers

0
deceze On Best Solutions

The specific error means that you have some other class Captcha probably in some other file which does not use a namespace, and that gets loaded. Somewhere you're jumbling up two different implementations of this class.

The problem is that your captcha class is not called Captcha, it's called Loader\Captcha. Since you're instantiating it from a string, that string needs to contain the fully qualified name of the class. Currently your code is looking for a class called Captcha, not Loader\Captcha.

Either do $loader->load('Loader\Captcha') and sort out the namespace internally somehow, or add the namespace internally:

$module_name = ucfirst($name);
$class = __NAMESPACE__ . '\\' . $module_name;
require_once __DIR__ . '/' . $module_name . '.php';
return new $class;

Again, this does not solve your issues with what's in what file though, since I can't see your files.