【发布时间】: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 函数)。
【问题讨论】:
标签: php class reflection constructor instantiation