简体   繁体   中英

Laravel 8 load dynamic class with namespace not found

I'm trying to load a dynamic class in my Laravel 8 controller. I have a database table of providers and a class column which matches a class in my project.

I'm currently doing the following in a controller method:

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $provider = DebtProvider::where('class', 'MyClass')->first();
    $toLoad = $provider->class;

    $class = new "App\\AssessmentProviders\\" . $toLoad($request);

    // ... do something with the $class methods etc
}

The issue is, I'm getting a syntax error:

message: "syntax error, unexpected '"App\\\\AssessmentProviders\\\\"' (T_CONSTANT_ENCAPSED_STRING)"

What am I missing?

You need to put the class namespace in a variable, then call new on it. Your namespace must not have ::class at the end, so be sure to remove it using str_replace

$class_namespace = str_replace("::class","", "App\AssessmentProviders\\" . $toLoad($request));
$class = new $class_namespace;

Also you can use app() method to create an instance of your desired class, this method will provide any required dependencies from service container.

$class = app("App\AssessmentProviders\" . $toLoad($request) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM