dongweishi2028 2018-03-23 15:12
浏览 52
已采纳

忽略未使用的类型参数并移至下一步

I've been searching alot, but I could not find any solution. I also don't exactly know if this is possible.

So here I have 2 cases somebody could do:

Case 1:

$callback = function(Object $obj, $var) {
    // Do stuff
}

Case 2:

$callback = function($var) {
    // Do stuff
}

Now I will call the function like this:

call_user_func_array($callback, [new Object, 'some text'])

But now there is a problem. In case 2 the $var will be seen as the object parameter. How do I send only the string parameter to the call when the object isn't used? And I don't want the order to change, the Object must be first.

P.S. I noticed that this is possible in the Symfony framework. I will continue researching how Symfony does this, any tips are appreciated!

Thanks for reading!

  • 写回答

1条回答 默认 最新

  • dpub33855 2018-03-24 23:31
    关注

    You can use reflection.

    Example:

    function call(callable $callback, $var, object $obj = null)
    {
        $callbackArguments = array();
        $parameters = (new ReflectionFunction($callback))->getParameters();
        foreach ($parameters as $parameter) {
            if ($parameter->getType() == 'object') {
                $callbackArguments[] = $obj;
            } else {
                $callbackArguments[] = $var;
            }
        }
        return call_user_func_array($callback, $callbackArguments);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题