2

i want to call function store inside array but before i do it i want to check if it is function,string or any other type.

please take a look at my code

$a=new stdClass();
$array = array(function() {
return "Bhavik Patel";
}, "1213",$a);

foreach ($array as $key => $value) {
    if (is_object($value)) {
        echo $value() . "<br/>";
    } else {
        echo $value . "<br/>";
    }
}

by doing this i can check if value is object then i call it but if i pass object it gives (pf course this will give error)

my intention is to find if value is function then call it.

4
  • Dear i know how to store function in array. please read carefully what i trying to do Commented Jan 24, 2014 at 6:42
  • @Jack Realized after I closed :) Commented Jan 24, 2014 at 6:59
  • can you now remove duplication mark? Commented Jan 24, 2014 at 7:00
  • We cannot take that, but don't worry, it won't be closed, and the box you are seeing, is only you who can see, not anyone else Commented Jan 24, 2014 at 7:02

3 Answers 3

3

To check specifically for anonymous functions you can test the value against \Closure like so:

if ($value instanceof \Closure) {
    echo $value(), "\n";
} else {
    echo $value;
}

The problem with is_callable() is that if your value is "explode", it will return true which is obviously not what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

@BhavikPatel Try $value = 'explode'; $value(); and you will see what I mean :)
0

is_callable() will help you, but notice that if you pass an array like this

array('object or class','method')

is_callable() return true, so you'd better to check it isn't an array

if (is_callable($value) && !is_array($value)) {.....}

see is_callable

2 Comments

A string can also be a callable :)
@Jack yeap, I miss that
0

Try [is_callable][1] in PHP. I have tested it, it works for me.

Comments

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.