jeudi 23 janvier 2020

PHP Reflection create class instance (object) with an array of arguments passed to the constructor

How to instantiate class Bar with PHP Reflection?

class code:

class Bar
{
    private $one;
    private $two;

    public function __construct($one, $two) 
    {
        $this->one = $one;
        $this->two = $two;
    }

    public function get()
    {
        return ($this->one + $this->two);
    }
}

I ran out of ideas, some of my guesswork is:

$class = 'Bar';
$constructorArgumentArr = [2,3];
$reflectionMethod = new \ReflectionMethod($class,'__construct');
$object = $reflectionMethod->invokeArgs($class, $constructorArgumentArr);

echo $object->get(); //should echo 5

but this will not work since invokeArgs() requires an object not a class name so I have a chicken-egg case: I don't have an object so I cannot use constructor method and I need to use constructor method to get the object.

I tried to pass null as $class as the first argument following the logic that constructor is called at the time when there's no object yet but I got: "ReflectionException: Trying to invoke non static method ..."

If there is no solution available by Reflection I'll accept any other (ie php function).

References:
Reflection Method
ReflectionMethod::invokeArgs





Aucun commentaire:

Enregistrer un commentaire