Ad

Class Not Found When Creating A Class With Class Name Being A String

- 1 answer

I need to create classes based on the parameter passed to a function. I do it this way:

public function index($source)
    {
        if(in_array($source, ModuleManager::getAllModules()))
        {
            $provider = new $source();
            if($image)
            {
                return $provider->getAll(true);
            }
            else
            {
                return $provider->getAll(false);
            }
        }
    }

Notice that on line 5 I'm trying to create an object of class $source which will definitely be available. I understand that the above code is actually an eval call. I'm using Laravel 5.2 and the above code returns:

FatalThrowableError in ProcReqController.php line 19:
Fatal error: Class 'Example' not found

In the above error Example can be any class that I made. Now if I hard code the value of $source then it works just fine.

What am I getting that error?

Ad

Answer

I believe what's happening is PHP gets confused when you try to instantiate a class whose class name is in a variable and it has to do with imports.

Solution 1

Set your $class variable to the fully qualified class name including the namespace and it should work.

In this way, new $class() should work even while including parenthesis.

Solution 2

After further testing, it seems when you instantiate a variable class, it always assumes global namespace.

With this in mind, you can use class_alias to alias each of your classes. In config/app.php, you can add each class to the aliases array.

'aliases' => [
    ....

    'Example' => App\Example::class
]
Ad
source: stackoverflow.com
Ad