【问题标题】:PHP Reflection create class instance (object) with an array of arguments passed to the constructorPHP反射使用传递给构造函数的参数数组创建类实例(对象)
【发布时间】:2020-05-10 08:07:33
【问题描述】:

如何用 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:尝试调用非静态方法......”

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

参考:
Reflection Method
ReflectionMethod::invokeArgs

【问题讨论】:

    标签: php class reflection constructor instantiation


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2021-07-03
      • 2019-09-29
      相关资源
      最近更新 更多