这里是使用callable 作为参数的示例。
下面的wait_do_linebreak函数会休眠给定的时间,然后用给定的拖尾参数调用一个函数,然后回显一个换行符。
...$params 将拖尾参数打包到一个名为 $params 的数组中。在这里,它被用来将参数代理到可调用对象中。
在示例的最后,您将看到一个将可调用对象作为参数的本机函数。
<?php
function wait_do_linebreak($time, callable $something, ...$params)
{
sleep($time);
call_user_func_array($something, $params);
echo "\n";
}
function earth_greeting() {
echo 'hello earth';
}
class Echo_Two
{
public function __invoke($baz, $bat)
{
echo $baz, " ", $bat;
}
}
class Eat_Static
{
static function another()
{
echo 'Another example.';
}
}
class Foo
{
public function more()
{
echo 'And here is another one.';
}
}
wait_do_linebreak(0, 'earth_greeting');
$my_echo = function($str) {
echo $str;
};
wait_do_linebreak(0, $my_echo, 'hello');
wait_do_linebreak(0, function() {
echo "I'm on top of the world.";
});
wait_do_linebreak(0, new Echo_Two, 'The', 'Earth');
wait_do_linebreak(0, ['Eat_Static', 'another']);
wait_do_linebreak(0, [new Foo, 'more']);
$array = [
'jim',
'bones',
'spock'
];
$word_contains_o = function (string $str) {
return strpos($str, 'o') !== false;
};
print_r(array_filter($array, $word_contains_o));
输出:
hello earth
hello
I'm on top of the world.
The Earth
Another example.
And here is another one.
Array
(
[1] => bones
[2] => spock
)