Blogger Information
Blog 31
fans 0
comment 0
visits 14269
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
函数的参数与返回值,匿名函数,回调函数
木子木杉
Original
590 people have browsed it

参数

参数:可选的,对外提供一个接口,供函数调用者按照自己的意愿改变函数体内的执行行为
参数 形参 实参
默认参数:有默认值的参数,如果不传参或者少传参,就会默认参数的值
参数是从左往右求值,所以默认参数在最右边
按值传递参数 不会改变全局变量的值 导入到函数中的只是$roomprice的副本

  1. function totalneedtopay1($days, $roomprice, $discount = 0.88)
  2. {
  3. $roomprice *= $discount;
  4. $total = $days * $roomprice;
  5. return "您需要支付的总价为{$total}元。";
  6. }
  7. $days = 5;
  8. $roomprice = 1500;
  9. $discount = 0.7;
  10. echo totalneedtopay1($days, $roomprice, $discount);

按变量引用传值 会改变父作用域里变量的值 变量内容所处的内存地址会被导入的函数中

  1. function totalneedtopay2($days, &$roomprice, $discount = 0.88)
  2. {
  3. $roomprice *= $discount;
  4. $total = $days * $roomprice;
  5. return "您需要支付的总价为{$total}元。";
  6. }
  7. $days = 5;
  8. $roomprice = 1500;
  9. $discount = 0.7;
  10. echo totalneedtopay2($days, $roomprice, $discount);
  11. echo $roomprice;

返回值

return 返回值

  • 1函数只能返回单一的值,返回值的类型可以是任意类型
  • 2函数碰到return语句,立即结束程序执行,return后面代码不会被执行
    1. function demo()
    2. {
    3. return md5('123456');
    4. return 1 === '1';
    5. return 1 == '1';
    6. return array('123', '西门子');
    7. return 12.23;
    8. echo '你好';
    9. return 1;
    10. }
    11. $res = demo();
    12. var_dump($res);

    匿名函数

    匿名函数 通常被当做回调函数参数来使用
    1. $closure = function ($name) {
    2. return "{$name},欢迎您下榻喜来登酒店。";
    3. };
    4. echo $closure('李女士');

    回调函数

    回调函数:php回调是指在主线程函数执行的过程中,突然跳去执行设置的回调函数,回调函数执行结束后, 再回到主线程处理接下来的流程
    1. $odd = function (array $arr) {
    2. for ($i = 0; $i < count($arr); $i++) {
    3. if ($arr[$i] % 2 == 0) {
    4. $newArr[] = $arr[$i];
    5. }
    6. }
    7. return $newArr;
    8. };
    9. $arr = [24, 36, 55, 87, 96, 24, 65, 66];
    10. var_dump($odd($arr));
    11. function sum(closure $func, $arr)
    12. {
    13. return array_sum($func($arr));
    14. }
    15. echo sum($odd, $arr);
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
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