博主信息
博文 47
粉丝 3
评论 0
访问量 50684
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
函数作用域与闭包、回调使用场景与参数调用、函数的多值返回
原创
916人浏览过

1. 函数作用域与闭包

  1. <?php
  2. // 1.函数作用域
  3. $name = '天蓬老师';
  4. $email = 'tp@php.cn';
  5. function demo1(): string
  6. {
  7. // 1.global
  8. global $name;
  9. $res .= 'name = ' .$name . '<br>';
  10. // 2.$GLOBALS
  11. $res .= 'email = ' .$GLOBALS['email'] . '<br>';
  12. return $res;
  13. }
  14. echo demo1();
  15. echo '<hr>';
  16. // 2.闭包:使用use()
  17. $demo2 = function () use ($name,$email) {
  18. return sprintf('name = %s<br>email = %s<br>',$name,$email);
  19. };
  20. echo $demo2()
  21. ?>

2. 回调的使用场景与参数调用

回调的使用场景:php单线程同步执行,遇到耗时函数时阻塞,可以改为回调函数异步执行

  1. <?php
  2. // 回调执行
  3. function demo1(string $name): string
  4. {
  5. return "Hello $name !";
  6. }
  7. // call_user_func(函数,参数列表)
  8. echo call_user_func('demo1','灭绝老师'), '<hr>';
  9. echo call_user_func_array('demo1',['php中文网']),'<br>';
  10. // 异步调用对象方法
  11. class User
  12. {
  13. // 实例方法
  14. public function hello(string $name) : string
  15. {
  16. return "Hello $name !";
  17. }
  18. // 静态方法:类调用
  19. public static function sum(string $site) :string
  20. {
  21. return "Hello $site !";
  22. }
  23. }
  24. // 实例方法
  25. $res = call_user_func_array([new User,'hello'],['天蓬老师']);
  26. echo $res,'<br>';
  27. // 静态方法
  28. $res = call_user_func_array('User::sum',['PHP中文网']);
  29. echo $res;
  30. ?>

3.函数的多值返回、内置序列化函数、json_encod()

  1. <?php
  2. // 数组
  3. function demo1():array
  4. {
  5. return ['status' => 1, 'message' => '成功'];
  6. }
  7. $res = demo1();
  8. print_r($res);
  9. echo '<hr>';
  10. // 对象
  11. function demo2():object
  12. {
  13. // 匿名类
  14. return new class ()
  15. {
  16. public $name = 'admin';
  17. public $email = 'admin@qq.com';
  18. };
  19. }
  20. $user = demo2();
  21. print_r($user);
  22. echo '<hr>';
  23. // php内置序列化函数:serialize
  24. function demo3(): string
  25. {
  26. return serialize(['status' => 1, 'message' => '验证成功']);
  27. }
  28. $str = demo3();
  29. echo $str;
  30. echo '<hr>';
  31. // 转为json:json_encode()
  32. function demo4(): string
  33. {
  34. return json_encode(['status' => 1, 'message' => '验证成功']);
  35. }
  36. $str = demo4();
  37. echo $str,'<br>';
  38. ?>
批改老师:天蓬老师天蓬老师

批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学