PHP闭包与函数回调
数组能够传递引用:
function fun($arr)
{
echo var_dump($arr);
$arr[0]=99;
$arr[1]=100;
}
$a=123;
$b=456;
fun(array(&$a,&$b));
{
echo var_dump($arr);
$arr[0]=99;
$arr[1]=100;
}
$a=123;
$b=456;
fun(array(&$a,&$b));
echo "$a,$b<br/>";
PHP5.3.0新增了闭包支持:
function funtest()
{
$a=18;
$b="Ly";
$fun=function($num,$name) use(&$a,&$b)
{
//echo "\$a:$a,\$b:$b<br/>";//输出
$a=$num;
$b=$name;
};
echo "$b:$a<br/>";
$fun(30,'wq');
echo "$b:$a<br/>";
}
funtest();
$fun=function($msg){
echo "$msg called by other function<br/>";
};
$fun("fun");
call_user_func($fun,"wq");
$name="array";
call_user_func_array($fun,array(&$name));
{
$a=18;
$b="Ly";
$fun=function($num,$name) use(&$a,&$b)
{
//echo "\$a:$a,\$b:$b<br/>";//输出
$a=$num;
$b=$name;
};
echo "$b:$a<br/>";
$fun(30,'wq');
echo "$b:$a<br/>";
}
funtest();
$fun=function($msg){
echo "$msg called by other function<br/>";
};
$fun("fun");
call_user_func($fun,"wq");
$name="array";
call_user_func_array($fun,array(&$name));
函数回调:
$arr=array(6,5,8,9,0,2,2);
function sortarr($a,$b)
{
return $a>$b?1:-1;
}
usort($arr,"sortarr");
foreach($arr as $e)
{
echo "$e,";
}
echo "<br/>";
function sortarr($a,$b)
{
return $a>$b?1:-1;
}
usort($arr,"sortarr");
foreach($arr as $e)
{
echo "$e,";
}
echo "<br/>";
usort($arr,create_function('$a,$b','return $a>$b?-1:1;'));
//注意,这里使用create_function创建匿名函数,一定要使用单引号,否则会报错
foreach($arr as $e)
{
echo "$e,";
}
{
echo "$e,";
}
//匿名函数的调用
call_user_func(function (){echo "<br/>ff";});
call_user_func(create_function('','echo "<br/>ff";'));
call_user_func(create_function('','echo "<br/>ff";'));
自己写的函数进行函数回调:
<?php
function fun($fun,$num)
{
$fun($num);
}
function writenum()
{
echo func_get_arg(0)."<br/>";
}
fun(create_function('$num','echo "$num<br/>";'),123);
fun("writenum",123);
fun(function(){echo func_get_arg(0)."<br/>";},123);
?>
{
$fun($num);
}
function writenum()
{
echo func_get_arg(0)."<br/>";
}
fun(create_function('$num','echo "$num<br/>";'),123);
fun("writenum",123);
fun(function(){echo func_get_arg(0)."<br/>";},123);
?>