Home >Backend Development >PHP Tutorial >PHP,求一个函数作为参数的例子?

PHP,求一个函数作为参数的例子?

WBOY
WBOYOriginal
2016-06-06 20:14:12990browse

<code><?php function foo($function) {
$function(" World");
}
function bar($params) {
echo "Hello".$params;
}

$variable = 'bar';
foo($variable);</code></code>

这段代码不太靠谱,感觉$variable不好区分是string还是函数

回复内容:

<code><?php function foo($function) {
$function(" World");
}
function bar($params) {
echo "Hello".$params;
}

$variable = 'bar';
foo($variable);</code></code>

这段代码不太靠谱,感觉$variable不好区分是string还是函数

匿名函数

<code>function f1(callable $f)
{
    return function ($iterator) use ($f){
            return $f($iterator);
        };
}
</code>

如果你想判断一个$var是否是函数(准确的说是否可被调用),可以使用is_callable($var)这个函数进行判断。或者在定义参数上直接使用function foo(callable $function)进行限制。

判断是否存在函数

<code class="php">function foo($function) {
    if(!function_exists($function)){
        die('没有该函数');
    }
    $function(" World");
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn