Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save POMXARK/9bd94081d3f2804dc8adb3bac760f113 to your computer and use it in GitHub Desktop.
Save POMXARK/9bd94081d3f2804dc8adb3bac760f113 to your computer and use it in GitHub Desktop.
<?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