gpt4 book ai didi

php - 如何使用 'function handling' 样式函数实例化一个类?

转载 作者:行者123 更新时间:2023-12-04 06:36:14 25 4
gpt4 key购买 nike

我正在尝试实现命令模式样式队列,但我不知道如何将参数传递给对象的构造函数。

我的“命令”模式将对象存储在数据库中,其中有一个表 queue_items使用字段 class 存储我的“命令”对象, method , constructor_arguments (存储为索引数组),method_arguments (存储为索引数组)和object_type (即 enum{'instance','static} )。

如果 object_type是“实例”,我使用"new"关键字实例化对象。如果 object_type是“静态的”,那么我只需使用 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() ,我找不到让我这样做的功能。

我希望保留索引数组而不依赖专门的构造函数,这样我就不必重写我自己的和我用来处理的第 3 方类,例如,将关联数组作为构造函数中的唯一参数。

有谁知道如何将索引数组直接传递到 __constructcall_user_func_array() 的方式?还是根本做不到?

德鲁·J·索恩。

最佳答案

您可以使用 ReflectionClass对于这种特殊情况:

$rc = new ReflectionClass($className);
$instance = $rc->newInstanceArgs($array_of_parameters);

关于php - 如何使用 'function handling' 样式函数实例化一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4840775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com