Blogger Information
Blog 5
fans 0
comment 0
visits 2033
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0806-请实例演绎你对回调函数与递归函数的理解?
马勇*JackMa
Original
413 people have browsed it

回调函数

  1. //命名函数作为回调函数
  2. function sum($n){ //数组求和
  3. $result = 0;
  4. for($i = 0;$i<count($n);$i++) $result += $n[$i];
  5. return $result;
  6. }
  7. function printArr($arr,$callback){ //打印数组中每一项的值,并利用回调函数求和
  8. foreach($arr as $value) echo $value.'<br>';
  9. return $callback($arr);
  10. }
  11. echo '求和结果为:'. printArr([1,89,34],'sum');
  12. ob_clean();
  13. //匿名函数作为回调函数
  14. $sum = function ($n){ //数组求和
  15. $result = 0;
  16. for($i = 0;$i<count($n);$i++) $result += $n[$i];
  17. return $result;
  18. } ;
  19. echo '求和结果为:'. printArr([1,89,34],$sum);

在网络请求或执行复杂业务逻辑时,需要耗费大量的时间,有可能会造成线程阻塞,影响代码的执行效率,就需要用使用系统提供的call_user_func()或者call_user_func_array()来执行回调

  • call_user_func(‘callback’,’参数1’,’参数2’,…);
  • call_user_func_array(‘callback’,[‘参数1’,’参数2’]);

递归函数

  1. //求3-100之间的正整数之和
  2. $count = 0;
  3. function compSum($n1,$n2){
  4. global $count;
  5. if($n1 <= $n2 ){
  6. $count += $n1;
  7. compSum(++$n1,$n2);
  8. }
  9. return $count;
  10. }
  11. echo '3到100之和:'.compSum(1,100);
  12. //递归的思维还有待提升,很容易把人绕晕,我这个递归的demo有点太牵强
Correcting teacher:PHPzPHPz

Correction status:unqualified

Teacher's comments:你这个递归函数使用后的计算结果真的是3-100之和吗?
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post