質問

How can we check for anonymous functions inside PHP arrays?

Example:

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

Can we then just simply use in_array, and to something like this:

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

I'm experimenting with method chaining and PHP's Magic Methods, and I've come to the point where I provide some functions anonymously, and just want to check if they are defined, but I wish not to loop through the object, nor to use gettype, or anything similar.

役に立ちましたか?

解決

You can filter the array by checking if the value is an instance of 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';
}

Pretty much, just check if the element of the array is an instance of Closure. If it is, you have a callable type.

他のヒント

Nickb's answer is great for figuring out if it is an anonymous function, but you may also use is_callable to figure out if it is any type of function ( probably more safe to assume )

For example

$x = function() { die(); }
$response = action( array( $x ) );
...
public function action( $array ){
    foreach( $array as $element )
        if( is_callable( $element ) ) 
           ....
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top