且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

推导PHP Closure参数

更新时间:2023-11-06 09:43:10

使用 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