推导PHP Closure参数 [英] Deducing PHP Closure parameters

查看:201
本文介绍了推导PHP Closure参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有机会,我可以推导出PHP Closure参数类型信息?考虑这个例子:

Is there any chance that I can deduce PHP Closure parameters type information? Consider this example:

<?php

$foo = function(array $args)
{
    echo $args['a'] . ' ' . $args['b'];
};

$bar = function($a, $b)
{
    echo $a . ' ' . $b;
};

$closure = /* some condition */ $foo : $bar;

if(/* $closure accepts array? */)
{
    call_user_func($closure, ['a' => 5, 'b' => 10]);
}
else
{
    call_user_func($closure, 5, 10);
}

?>

我想给用户留下一些自由,所以他或她可以决定哪种方式更好地定义将在我的分派器中注册的关闭 - 将接受关联数组中的参数或直接作为Closure参数。因此,dispatcher需要推断出传递的Closure的参数,以确定它应该称之为Closure的方式。任何想法?

I want to leave some freedom for user so he or she could decide which way is better to define a Closure that will be registered in my dispatcher - will it accept parameters in associative array or directly as Closure parameters. So, dispatcher need to deduce parameters of the passed Closure to determine which way should it call this Closure. Any ideas?

推荐答案

使用 reflection ,如果你需要做出决定,基于代码结构。在您的情况下, ReflectionFunction ReflectionParameter 是您的朋友。

Use reflection, if you need to make decisions, based on code structure. In your case ReflectionFunction and ReflectionParameter are your friends.

<?php
header('Content-Type: text/plain; charset=utf-8');

$func = function($a, $b){ echo implode(' ', func_get_args()); };

$closure    = &$func;
$reflection = new ReflectionFunction($closure);
$arguments  = $reflection->getParameters();

if($arguments && $arguments[0]->isArray()){
    echo 'Giving array. Result: ';
    call_user_func($closure, ['a' => 5, 'b' => 10]);
} else {
    echo 'Giving individuals. Result: ';
    call_user_func($closure, 5, 10);
}
?>

输出:

Giving individuals. Result: 5 10

将定义更改为测试:

$func = function(array $a){ echo implode(' ', $a); };

输出:

Giving array. Result: 5 10

这篇关于推导PHP Closure参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆