John Davidson

php - Laravel, resolve dependecy by passing class name as string

0 comments
Message:


When I try to resolve a dependecy class like this


app(MyClass::class);

it works perfectly, but what I actually need is to pass the name of the class like a string, something similar to this:


$className = 'MyClass';
app($className::class);

I tried using reflection and every possible way but without success.



My Answer:
In order to resolve a dependency by passing the class name as a string, you can use the `app()->make()` method instead of `app()`. Here's how you can achieve this:

php
$className = 'MyClass';
$instance = app()->make($className);


This will resolve the dependency using the class name provided as a string.

Rate this post

5 of 5 based on 3460 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us