Forked from omarkdev/introduction-php-reflection-reflection-class-get-constructor.php
Created
June 7, 2024 14:13
-
-
Save POMXARK/9bd94081d3f2804dc8adb3bac760f113 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