Heim  >  Artikel  >  Backend-Entwicklung  >  PHP,求一个函数作为参数的例子?

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

WBOY
WBOYOriginal
2016-06-06 20:14:12965Durchsuche

<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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn