duanju6788 2012-09-27 19:57
浏览 23
已采纳

动态调用类方法Args

I am working on something where I need to be able to pass an indexed array of args to a method, much like how call_user_func_array works. I would use call_user_func_array but it is not an OOP approach, which is undesired, and it requires the method to be static, which breaks the target class's OO.

I have tried to use ReflectionClass but to no avail. You cannot invoke arguments to a method of the class, only the constructor. This is unfortunately, not desireable.

So I took to the man pages and looked at ReflectionFunction but there is no way to instantiate the class, point it to a method, and then invokeArgs with it.

Example using ReflectionFunction ( remember, this question is tagged PHP 5.4, hence the syntax):

$call = new \ReflectionFunction( "(ExampleClass())->exampleMethod" );
$call->invokeArgs( ["argument1", "argument2"] );

This fails with:

Function (Index())->Index() does not exist

Example using ReflectionMethod

$call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
$call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
print_r( $call );

This fails with:

ReflectionMethod Object
(
    [name] => Index
    [class] => Index
)

The arguments are never passed to the method.

The desired results are:

class ExampleClass() {
    public function exampleMethod( $exampleArg1, $exampleArg2 ){
        // do something here
        echo "Argument 1: {$exampleArg1}
";
        echo "Argument 2: {$exampleArg2}
";
    }
}

$array = [ 'exampleArg1Value', 'exampleArg2Value' ];

If I passed $array to an instance of ExampleClass->exampleMethod(), I would only have one argument, which would be an array. Instead, I need to be able to pull the individual arguments.

I was thinking that if there was a way to call ReflectorFunction on a ReflectorClass I would in in ship-shape and on my way, but it doesn't look like that is possible.

Does anyone have anything they have used to accomplish this previously?

  • 写回答

3条回答 默认 最新

  • douguanya4248 2012-09-28 13:49
    关注

    For some reason, something got stuck, somewhere.

    $call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
    $call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
    

    Now returns

    Argument 1: argument1
    Argument 2: argument2
    

    I am going to try to reproduce the issue. It is on a fresh php 5.4.7 install with php-cli and fpm.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False