PHP-常用回調(diào)函數(shù)

1.匿名函數(shù)


$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.對象方法數(shù)組:


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.字符串函數(shù)名call_user_func


functionbarber($type)

{

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

}

call_user_func('barber',"mushroom");

call_user_func('barber',"shave");

?>

4.腳本執(zhí)行完后 回調(diào)函數(shù)

register_shutdown_function()這個函數(shù),能夠在腳本終止前回調(diào)注冊的函數(shù),也就是當 PHP 程序執(zhí)行完成后執(zhí)行的函數(shù)。

register_shutdown_function 執(zhí)行機制是:PHP把要調(diào)用的函數(shù)調(diào)入內(nèi)存。當頁面所有PHP語句都執(zhí)行完成時,再調(diào)用此 函數(shù)。注意,在這個時候從內(nèi)存中調(diào)用,不是從PHP頁面中調(diào)用,所以上面的例子不能使用相對路徑,因為PHP已經(jīng)當原來的頁面不存在了。就沒有什么相對路 徑可言。


functionshutdown()

{

echo'Script?executed?with?success',PHP_EOL;

}

register_shutdown_function('shutdown');

?>

5.數(shù)組排序回調(diào)


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.正則回調(diào)


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

returnstrtoupper($match[1]);

},'hello-world');

//?輸出?helloWorld

?>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容