search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

首页课程PHP Fun Breakthrough ClassAnonymous function of custom function

Anonymous function of custom function

目录列表

匿名函数

所谓匿名,就是没有名字:匿名函数,也就是没有函数名的函数。

匿名函数的第一种用法,直接把赋数赋值给变量,调用变量即为调用函数。

匿名函数的写法比较灵活。

1.变量函数式的匿名函数:

<?php
$greet = function($name)
{
 echo $name.',你好';
};
$greet('明天');
$greet('PHP中文网');
?>

上例中的函数体没有函数名,通过$greent加上括号来调用的,这就是匿名函数。

2.回调式的匿名函数:

我们将之前的例子拿过来。实际使用场景中,我们要通过一个函数实现更多的功能。但是,我又不想专门定义一个函数。我们回顾一下,我们回调函数的例子:

<?php
function woziji($one,$two,$func){
       //我规定:检查$func是否是函数,如果不是函数停止执行本段代码,返回false
       if(!is_callable($func)){
               return false;
       }
       //我把$one、$two相加,再把$one和$two传入$func这个函数中处理一次
       echo $one + $two + $func($one,$two);
}
woziji(20,30,function( $foo , $bar){

               $result = ($foo+$bar)*2;

               return $result;
           }
);
?>

仔细推理一下过程哟。只不过在之前的章节当中,plusx2换成了我们的匿名函数:

<?php
function( $foo , $bar){
       $result = ($foo+$bar)*2;
       return $result;
}
?>

因此,函名函数在调用的时候没有函数时。我们可以采用以上的一些方法来使用匿名函数。

&lt;?php $func = function( $param ) { echo $param; }; $func( 'hello, php.cn' ); ?&gt; 这段代码会输出内容嘛?

1/2