Search code examples
phpanonymous-functionmethod-chainingmagic-methods

Check for anonymous functions in PHP arrays?


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.


Solution

  • 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.