PHP反射创建类实例(对象),并将参数数组传递给构造函数

问题描述 投票:0回答:1

如何使用PHP Reflection实例化类Bar?

类代码:

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);
    }
}

我没了主意,我的一些猜测是:

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

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

但是这将不起作用,因为invokeArgs()要求的对象不是类名,所以我有一个鸡蛋案:我没有对象,所以我不能使用构造函数方法,我需要使用构造函数方法来获取宾语。

我尝试将null作为第一个参数传递为$class,这是在没有对象但当时得到对象的时候调用构造函数的逻辑,我得到:“ ReflectionException:试图调用非静态方法...”

如果Reflection没有可用的解决方案,我将接受其他任何解决方案(即php函数)。

参考:Reflection MethodReflectionMethod::invokeArgs

php class reflection constructor instantiation
1个回答
1
投票

您可以使用ReflectionClassReflectionClass::newInstanceArgs

    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);
        }
    }

    $args = [2, 3];
    $reflect  = new \ReflectionClass("Bar");
    $instance = $reflect->newInstanceArgs($args);
    echo $instance->get();
© www.soinside.com 2019 - 2024. All rights reserved.