检查PHP数组中的匿名函数?

检查PHP数组中的匿名函数?,php,anonymous-function,method-chaining,magic-methods,Php,Anonymous Function,Method Chaining,Magic Methods,我们如何检查PHP数组中的匿名函数 例如: $array = array('callback' => function() { die('calls back'); }); 然后,我们可以简单地在数组中使用,并执行如下操作: if( in_array(function() {}, $array) ) { // Yes! There is an anonymous function inside my elements. } else { // Nop! There

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

例如:

$array = array('callback' => function() {
    die('calls back');
});
然后,我们可以简单地在数组中使用
,并执行如下操作:

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
,或任何类似内容。

您可以通过检查值是否为
闭包的实例来筛选数组:

$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
的实例。如果是,则有一个可调用类型

您可以通过检查值是否是
闭包的实例来筛选数组:

$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
的实例。如果是,则有一个可调用类型

Nickb的答案对于判断它是否是匿名函数非常有用,但您也可以使用is_callable来判断它是否是任何类型的函数(假设可能更安全)

比如说

$x = function() { die(); }
$response = action( array( $x ) );
...
public function action( $array ){
    foreach( $array as $element )
        if( is_callable( $element ) ) 
           ....
}

Nickb的答案对于判断它是否是匿名函数非常有用,但您也可以使用is_callable来判断它是否是任何类型的函数(假设可能更安全)

比如说

$x = function() { die(); }
$response = action( array( $x ) );
...
public function action( $array ){
    foreach( $array as $element )
        if( is_callable( $element ) ) 
           ....
}

我怀疑。in_数组只查找值,每个闭包将有不同的值,即使“代码”相同。对此表示怀疑。in_数组只查找值,每个闭包将有不同的值,即使“代码”相同。