0

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 function or if $func['hello'] is function?

Thanks.

1
  • Try to change the if to do the reverse: if (is_callable($func)) $func; else $func['hello'](); Commented Oct 3, 2016 at 16:03

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

is_callable is just function, never know if another was called or not, in first is_callable($func) is not important what value is in variable $func because function is_callable will check if its callable, before you use $func['hello'] you must know that $func is an array thats why
just the value of variable will pass to function throught parameter, so some_function([]); is the same as $array = []; some_function($array); in context of the function
when you write $func['hello'] you read value of array $func with key hello, if $func is not array then error will occur
just try something like $string = 'test'; $string[0]; or $array = ['test']; echo $array; or $array = ['test']; $array['whatever']; all of them will fail...
that means the type of value is important for functions because they know how to handle only that types for which they are prepared to work
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.