首页 > 解决方案 > PHP反射使用传递给构造函数的参数数组创建类实例(对象)

问题描述

如何使用 PHP 反射实例化类 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() 需要一个对象而不是类名,所以我有一个鸡蛋情况:我没有对象,所以我不能使用构造函数方法,我需要使用构造函数方法来获取对象。

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

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

参考:
反射方法
ReflectionMethod::invokeArgs

标签: phpclassreflectionconstructorinstantiation

解决方案


您可以使用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();

推荐阅读