PHP 反射创建 class 实例(对象),并将参数数组传递给构造函数
PHP Reflection create class instance (object) with an array of arguments passed to the constructor
如何使用 PHP 反射实例化 class 条形图?
class代码:
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 作为 $class
作为第一个参数传递,遵循在还没有对象时调用构造函数的逻辑,但我得到:"ReflectionException: Trying to invoke non static method ..."
如果 Reflection 没有可用的解决方案,我将接受任何其他解决方案(即 php 函数)。
你可以使用 ReflectionClass and ReflectionClass::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();
如何使用 PHP 反射实例化 class 条形图?
class代码:
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 作为 $class
作为第一个参数传递,遵循在还没有对象时调用构造函数的逻辑,但我得到:"ReflectionException: Trying to invoke non static method ..."
如果 Reflection 没有可用的解决方案,我将接受任何其他解决方案(即 php 函数)。
你可以使用 ReflectionClass and ReflectionClass::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();