Cristian Crishk Cristian Crishk - 2 months ago 17
PHP Question

How to execute function when parameter is array or callable?

Look this example code:

I'm getting the error: Fatal error: Uncaught Error: Cannot use object of type Closure as array in C:\xampp\htdocs\dermaquality\test.php:11 Stack trace: #0 C:\xampp\htdocs\dermaquality\test.php(20): test(Object(Closure)) #1 {main} thrown in

$array = array(
'hello' => function() {
echo "HEllo world";
}
);

function test( $func )
{
if (is_callable( $func['hello'] )) {
$func['hello']();
}
else {
$func();
}
}

echo "Executing 1 <br/>";
test( $hello = function() {"Hello world";} );
echo "Executing 2 <br/>";
test( $array['hello'] );
exit;


How can I call $func if $func is a function or if $func['hello'] is function?

Thanks.

Answer

Problem is in if (is_callable( $func['hello'] )) { because you dont know if $func is an array.. btw you dont put array as parameter in test( $array['hello'] ); you put just function...

function test( $func )
{
    if (is_callable($func)) {
        $func();
    }
    else if (is_array($func)){
        if(isset($func['hello']) && is_callable($func['hello'])){
            $func['hello']();
        }else{
            // unknown what to call
        }
    }else{
        // unknown what to call
    }
}