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<$b)???-1:1;
}
$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
?>