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.

62 lines
1.4 KiB

2 years ago
  1. <?php
  2. function math($opt_name,$m,$n)
  3. {
  4. echo "this is a math opt '$opt_name'".'<br>';
  5. return $opt_name($m,$n);
  6. }
  7. function add($m,$n)//回调函数
  8. {
  9. return $m+$n;
  10. }
  11. function subtraction($m,$n)
  12. {
  13. return $m-$n;
  14. }
  15. $ret=math('add',1,2);
  16. echo $ret.'<br>';
  17. $ret=math('subtraction',6,4);
  18. echo $ret.'<br>';
  19. /*
  20. * add是回调函数,add作为参数传入math()中,
  21. * 这样就可以把add(),和subtraction()公有的部分一起放入math()中,例如 echo "this is a math opt '$opt_name'".'<br>';
  22. * 如果math作为库函数,我们是不能修改的。
  23. * 如果不适用回调函数,那么代码将会这样
  24. function add($m,$n)//回调函数
  25. {
  26. echo "this is a math opt 'add'".'<br>';
  27. return $m+$n;
  28. }
  29. function subtraction($m,$n)
  30. {
  31. echo "this is a math opt 'subtraction'".'<br>';
  32. return $m-$n;
  33. }
  34. $ret=add(1,2);
  35. echo $ret.'<br>';
  36. $ret=subtraction(6,4);
  37. echo $ret.'<br>';
  38. */
  39. //call_user_func()
  40. $ret=call_user_func('add',10,5);
  41. echo $ret.'<br>';
  42. //call_user_func_array()
  43. function func_b($funcName,$m,$n)
  44. {
  45. return call_user_func_array($funcName, array($m,$n)); //以数组的形式接收回调函数的参数
  46. }
  47. $ret=func_b('add',2,100);
  48. echo $ret.'<br>';
  49. ?>