Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

Why and how do you use anonymous functions in PHP?

Anonymous functions are available from PHP 5.3.
Should I use them or avoid them? If so, how?

Edited; just found some nice trick with php anonymous functions...

$container           = new DependencyInjectionContainer();
$container->mail     = function($container) {};
$conteiner->db       = function($container) {};
$container->memcache = function($container) {};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:

$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
$arr_square = array_map(function($val) { return $val * $val; }, $arr);

Otherwise you would need to define a function that you possibly only use once:

function isEven($val) { return $val % 2 == 0; }
$arr_even = array_filter($arr, 'isEven');
function square($val) { return $val * $val; }
$arr_square = array_map('square', $arr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...