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

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

WBOY
Release: 2016-06-06 20:14:12
Original
989 people have browsed it

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

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

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

回复内容:

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

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

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

匿名函数

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

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

判断是否存在函数

<code class="php">function foo($function) {
    if(!function_exists($function)){
        die('没有该函数');
    }
    $function(" World");
}</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template