Php 如何使用';函数处理';风格功能?
我试图实现一个命令模式样式的队列,但我不知道如何将参数传递给对象的构造函数 我的“Command”模式将对象存储在数据库中,在数据库中我有一个表Php 如何使用';函数处理';风格功能?,php,reflection,instantiation,Php,Reflection,Instantiation,我试图实现一个命令模式样式的队列,但我不知道如何将参数传递给对象的构造函数 我的“Command”模式将对象存储在数据库中,在数据库中我有一个表queue\u items存储我的“Command”对象,其中的字段有class、method、constructor\u arguments(存储为索引数组)、method\u arguments(存储为索引数组)和object\u type(这是enum{'instance','static}) 如果object\u type是'instance',
queue\u items
存储我的“Command”对象,其中的字段有class
、method
、constructor\u arguments
(存储为索引数组)、method\u arguments
(存储为索引数组)和object\u type
(这是enum{'instance','static}
)
如果object\u type
是'instance',我将使用'new'关键字实例化该对象。如果object\u type
是'static',那么我只需使用forward\u static\u call\u array()进行调用。
如果我没有构造函数参数,我可以这样使用:
$instance = new $class_name(); //NOTE: no arguments in the constructor
$result = call_user_func_array(array($instance, $method_name), $method_arguments);
但是,如果我希望将值从构造函数\u参数
传递到\u构造函数()
,我找不到一个函数来执行此操作
我希望保留索引数组,而不是依赖于专门的构造函数,这样我就不必重写自己的类和用于处理的第三方类,例如,将关联数组作为构造函数中的唯一参数
是否有人知道如何以调用用户函数数组()的方式将索引数组直接传递到\u构造中
Drew J.Sonne.对于这种特殊情况,您可以使用
ReflectionClass
:
$rc = new ReflectionClass($className);
$instance = $rc->newInstanceArgs($array_of_parameters);
使用ReflectionClass的更详细示例:
<?php
class MyClass
{
private $arg1;
private $arg2;
public function __construct($arg1, $arg2 = "Hello World")
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function print(){
echo $this->arg2 . "," .$this->arg2;
}
}
$class = new ReflectionClass('MyClass');
$args = array(3,"outro");
$instance = $class->newInstanceArgs($args);
$instance->print()
?>