Created
March 9, 2020 20:03
-
-
Save omarkdev/e7bde42e4d5f9a304ba76bccc2a3c4a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class UserRepository | |
{ } | |
class UserController { | |
private $userRepository; | |
public function __construct(UserRepository $repository) | |
{ | |
$this->userRepository = $repository; | |
} | |
} | |
$userReflected = new ReflectionClass(UserController::class); | |
var_dump($userReflected); | |
// object(ReflectionClass)#1 (1) { | |
// ["name"]=> | |
// string(14) "UserController" | |
//} | |
$constructorParameters = $userReflected->getConstructor()->getParameters(); | |
$argumentsToConstruct = []; | |
foreach ($constructorParameters as $parameter) { | |
$name = $parameter->getClass()->name; | |
var_dump($name); | |
// string(14) "UserRepository" | |
$instance = new $name(); | |
var_dump($instance); | |
// object(UserRepository)#2 (0) { | |
//} | |
$argumentsToConstruct[] = $instance; | |
} | |
$userController = new UserController(...$argumentsToConstruct); | |
var_dump($userController); | |
// object(UserController)#4 (1) { | |
// ["userRepository":"UserController":private]=> | |
// object(UserRepository)#2 (0) { | |
// } | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment