0

我们如何检查 PHP 数组中的匿名函数?

例子:

$array = array('callback' => function() {
    die('calls back');
});

然后我们可以简单地使用in_array, 和这样的东西:

if( in_array(function() {}, $array) ) {
    // Yes! There is an anonymous function inside my elements.
} else {
    // Nop! There are no anonymous function inside of me.
}

我正在尝试方法链接和 PHP 的魔术方法,我已经到了匿名提供一些函数的地步,只是想检查它们是否已定义,但我不希望循环遍历对象,也不使用gettype,或任何类似的东西。

4

2 回答 2

3

您可以通过检查值是否为以下实例来过滤数组Closure

$array = array( 'callback' => function() { die( 'callback'); });
$anon_fns = array_filter( $array, function( $el) { return $el instanceof Closure; });
if( count( $anon_fns) == 0) { // Assumes count( $array) > 0
    echo 'No anonymous functions in the array';
} else {
    echo 'Anonymous functions exist in the array';
}

差不多,只需检查数组的元素是否是Closure. 如果是,你有一个可调用的类型。

于 2013-04-19T18:54:08.537 回答
1

Nickb 的答案非常适合确定它是否是匿名函数,但您也可以使用 is_callable 来确定它是否是任何类型的函数(假设可能更安全)

例如

$x = function() { die(); }
$response = action( array( $x ) );
...
public function action( $array ){
    foreach( $array as $element )
        if( is_callable( $element ) ) 
           ....
}
于 2013-04-19T19:08:51.860 回答