我正在尝试实现命令模式样式队列,但我不知道如何将参数传递给对象的构造函数。
我的“命令”模式将对象存储在数据库中,其中有一个表 queue_items
存储我的“命令”对象,其中包含字段 class
、 method
、constructor_arguments
(存储为索引数组)、method_arguments
(存储为索引数组)和 object_type
(即枚举{'instance','static}
)。
如果object_type
是“instance”,我会使用“new”关键字实例化该对象。如果 object_type
为“static”,那么我只需使用 forward_static_call_array()
进行调用。
如果我没有构造函数参数,我可以使用这样的东西:
$instance = new $class_name(); //NOTE: no arguments in the constructor
$result = call_user_func_array(array($instance, $method_name), $method_arguments);
但是如果我希望将constructor_arguments
中的值传递到__construct()
中,我找不到一个函数可以让我这样做。
我希望保留索引数组而不是依赖于专门的构造函数,这样我就不必重写我自己的和我用来处理的第三方类,例如,将关联数组作为唯一的参数构造函数。
有谁知道如何以 call_user_func_array()
的方式将索引数组直接传递到 __construct
中?或者根本就不能完成?
德鲁·J·索恩。
最佳答案
对于这种特殊情况,您可以使用ReflectionClass
:
$rc = new ReflectionClass($className);
$instance = $rc->newInstanceArgs($array_of_parameters);
关于php - 如何使用 'function handling' 样式函数实例化一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4840775/