Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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 ) ) 
           ....
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top