Blogger Information
Blog 47
fans 3
comment 0
visits 38247
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
函数作用域与闭包、回调使用场景与参数调用、函数的多值返回
Original
707 people have browsed it

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. ?>
Correcting teacher:天蓬老师天蓬老师

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