13

Say that I have an array as follows:

array(
    [0] => function() { return "hello"; }
    [1] => function() { return "world"; }
    [2] => "look"
    [3] => function() { return "and";}
    [4] => function() { return "listen";}
)

Is there a way I can invoke 0, 1, 3 and 4 without invoking 2?

4

4 回答 4

16

匿名函数是Closure类的实例。因此,检查并is_callable完成工作。

foreach ($array as $func) {
    if (is_callable($func) && $func instanceof Closure) {
        $func();
    }
}

实际上,类检查就足够了,因为您不能Closure手动实例化对象,除非通过创建匿名函数。

于 2012-06-02T11:40:30.057 回答
1

You can use reflection, it has an undocument function to check for closures; try this (haven't tested):

foreach ($array as $val) {
    $re = newReflectionFunction($val);
    if ($re->isClosure()) {
        $val();
        // do whatever you want
    }
}

...or check whether it isn't a string/numeric:

foreach ($array as $val) {
    if (!is_string($val) && !is_numeric($val)) {
        $val();
        // do whatever you want
    }
}

...or check whether it's an object:

foreach ($array as $val) {
    if (gettype($val) == 'object') {
        $val();
        // do whatever you want
    }
}
于 2012-06-02T11:33:46.807 回答
1

我想这就是你想要的。$result将是每个函数调用的返回值的数组(除非它不是匿名函数,在这种情况下它将是来自 的原始值$array)。

$result = array_map(
                    function($e) {
                      return ($e instanceof Closure && is_callable($e)) ?
                        $e() : $e;
                    }, $array);
于 2012-06-02T11:43:06.237 回答
0

gettype在匿名方法上返回“对象”并is_callable()在函数上返回 true,然后:

foreach ($array as $val) {
    if (is_callable($val) && gettype($val)=="object") {
        $val();
    }
}

这是我的测试代码:

<?php 

function look(){
    return "looking";
}

$data=array(
    0 => function() { return "hello"; },
    1 => function() { return "world"; },
    2 => "look",
    3 => function() { return "and";},
    4 => function() { return "listen";}
);
echo "<pre>";

foreach ($data as $val) {
    if (is_callable($val) && gettype($val)=="object") {
        echo $val();
    }
}

?>
于 2012-06-02T11:36:03.550 回答