Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save omarkdev/e7bde42e4d5f9a304ba76bccc2a3c4a6 to your computer and use it in GitHub Desktop.

Select an option

Save omarkdev/e7bde42e4d5f9a304ba76bccc2a3c4a6 to your computer and use it in GitHub Desktop.

Revisions

  1. omarkdev created this gist Mar 9, 2020.
    45 changes: 45 additions & 0 deletions introduction-php-reflection-reflection-class-get-constructor.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    <?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) {
    // }
    //}