You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.2 KiB

<?php
/**
* 函数内部的无名函数
* 与普通函数一样有返回值
* 可以作为一个变量值使用
* 常用于做回调函数的参数
* 把匿名函数当成一个对象
*/
//1 匿名函数作为变量值
$a = function(){
echo 'hello'.PHP_EOL;
return "这是匿名函数的返回值";
};
$a();
echo $a().PHP_EOL; //output:会执行函数里的代码,并且返回返回值
//2 匿名函数的参数
$b=function($var){
echo $var.PHP_EOL;
return "返回".$var;
};
$b("匿名函数的参数");
echo $b("匿名函数的参数").PHP_EOL;
//2 匿名函数作为函数里的函数
function func(){
$b='父类中的变量';
//wrong output:Undefined variable: b
// $innerFunc = function(){
// //调用函数func的局部变量
// echo $b;
// };
//3 匿名函数调用父类中的变量
$innerFunc = function() use ($b){
echo "调用".$b.PHP_EOL;
};
//调用匿名函数
$innerFunc();
}
func();
//匿名函数作为参数,回调函数
//array_map(?callable $callback, array $array, array ...$arrays): array
//数组$array中的元素依次赋值到匿名函数中的$num
$arr=[1,2,3,4];
$ret = array_map(
function($num){
return $num * $num;
},
$arr);
print_r($ret);
//静态匿名函数
//匿名函数允许被定义为静态化。这样可以防止当前类自动绑定到它们身上,对象在运行时也可能不会被绑定到它们上面。
//不是很理解这句话
//在类中的匿名函数,不带static
class ClassA
{
public $a = 3;
function __construct()
{
$func = function(){
echo $this->a.PHP_EOL;
};
$func();
}
}
$obj=new ClassA();
//带static的匿名函数
class ClassB
{
public $a=4;
function __construct() {
$func=static function(){echo $this->a.PHP_EOL;}; //wrong output:Using $this when not in object context
$func();
}
}
$obj2=new ClassB();
?>