PHP custom function anonymous function
The so-called anonymity means having no name.
Anonymous function is a function without a function name.
The first usage of anonymous functions is to directly assign the assignment value to the variable, and calling the variable is to call the function.
The writing method of anonymous functions is more flexible.
1. Variable functional anonymous function
<?php $greet = function($name) { echo $name.',你好'; }; $greet('明天'); $greet('PHP中文网'); ?>
The function body in the above example has no function name and is called through $greent plus parentheses. This is anonymous function.
2. Callback-style anonymous function
Let’s take the previous example. In actual usage scenarios, we need to implement more functions through a function. However, I don't want to specifically define a function. Let’s review the example of our callback function:
<?php function woziji($one,$two,$func){ //我规定:检查$func是否是函数,如果不是函数停止执行本段代码,返回false if(!is_callable($func)){ return false; } //我把$one、$two相加,再把$one和$two传入$func这个函数中处理一次 //$func是一个变量函数,参见变量函数这一章 echo $one + $two + $func($one,$two); } woziji(20,30,function( $foo , $bar){ $result = ($foo+$bar)*2; return $result; } ); ?>
Let’s reason about the process carefully. It’s just that in the previous chapter, plusx2 was replaced by our anonymous function:
<?php function( $foo , $bar){ $result = ($foo+$bar)*2; return $result; } ?>
Therefore, the function name function does not have a function name when it is called. We can use anonymous functions in some of the above ways.