php回调匿名回调函数,PHP-常用回调函数

1.匿名函数

$message='hello';

// 没有 "use"

$example= function () {

var_dump($message);

};

echo$example();

// 继承 $message

$example= function () use ($message) {

var_dump($message);

};

echo$example();

// Inherited variable's value is from when the function

// is defined, not when called

$message='world';

echo$example();

// Reset message

$message='hello';

// Inherit by-reference

$example= function () use (&$message) {

var_dump($message);

};

echo$example();

// The changed value in the parent scope

// is reflected inside the function call

$message='world';

echo$example();

// Closures can also accept regular arguments

$example= function ($arg) use ($message) {

var_dump($arg.' '.$message);

};

$example("hello");

?>

2.对象方法数组:

function myfunction($value,$key,$p)

{

echo "$key $p $value

";

}

$a=array("a"=>"red","b"=>"green","c"=>"blue");

array_walk($a,"myfunction","has the value");

3.字符串函数名call_user_func

functionbarber($type)

{

echo"You wanted a$typehaircut, no problem\n";

}

call_user_func('barber',"mushroom");

call_user_func('barber',"shave");

?>

4.脚本执行完后 回调函数

register_shutdown_function()这个函数,能够在脚本终止前回调注册的函数,也就是当 PHP 程序执行完成后执行的函数。

register_shutdown_function 执行机制是:PHP把要调用的函数调入内存。当页面所有PHP语句都执行完成时,再调用此 函数。注意,在这个时候从内存中调用,不是从PHP页面中调用,所以上面的例子不能使用相对路径,因为PHP已经当原来的页面不存在了。就没有什么相对路 径可言。

functionshutdown()

{

echo'Script executed with success',PHP_EOL;

}

register_shutdown_function('shutdown');

?>

5.数组排序回调

functioncmp($a,$b)

{

if ($a==$b) {

return0;

}

return ($a

}

$a= array(3,2,5,6,1);

usort($a,"cmp");

foreach ($aas$key=>$value) {

echo"$key:$value\n";

}

?>

6.正则回调

echopreg_replace_callback('~-([a-z])~', function ($match) {

returnstrtoupper($match[1]);

},'hello-world');

// 输出 helloWorld

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值