博主信息
博文 19
粉丝 1
评论 0
访问量 16412
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
#PHP函数的返回值,参数,匿名函数
▽空城旧梦
原创
1497人浏览过

函数的返回值

1.函数使用return返回单个值
2.多个值的返回,可以用数组的形式返回
3.函数可以返回object对象。
4.函数可以返回json字符串。

json_encode(字符串,第二参数)
json字符串参数 256中文不转义
json字符串 64不转义/
可以叠加使用 256+64

5.以序列化字符串返回,常用于记录日志

函数的参数

1.引用参数
引用参数,在函数里面发生变化,都会对父级产生影响。
2.剩余参数
包含 … 的参数,会转换为指定参数变量的一个数组

  1. <?php
  2. function sum(...$numbers) {
  3. $acc = 0;
  4. foreach ($numbers as $n) {
  5. $acc += $n;
  6. }
  7. return $acc;
  8. }
  9. echo sum(1, 2, 3, 4);
  10. ?>

3.默认参数

  1. <?php
  2. function makeyogurt($flavour, $type = "acidophilus")
  3. {
  4. return "Making a bowl of $type $flavour.\n";
  5. }
  6. echo makeyogurt("raspberry"); // works as expected
  7. ?>

匿名函数

匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数 callable参数的值。当然,也有其它应用的情况。

匿名函数目前是通过 Closure 类来实现的。

  1. <?php
  2. $greet = function($name)
  3. {
  4. printf("Hello %s\r\n", $name);
  5. };
  6. $greet('World');
  7. $greet('PHP');
  8. ?>

闭包可以从父作用域中继承变量。

  1. <?php
  2. $message = 'hello';
  3. // 没有 "use"
  4. $example = function () {
  5. var_dump($message);
  6. };
  7. $example();
  8. // 继承 $message
  9. $example = function () use ($message) {
  10. var_dump($message);
  11. };
  12. $example();
  13. // Inherited variable's value is from when the function
  14. // is defined, not when called
  15. $message = 'world';
  16. $example();
  17. // Reset message
  18. $message = 'hello';
  19. // Inherit by-reference
  20. $example = function () use (&$message) {
  21. var_dump($message);
  22. };
  23. $example();
  24. // The changed value in the parent scope
  25. // is reflected inside the function call
  26. $message = 'world';
  27. $example();
  28. // Closures can also accept regular arguments
  29. $example = function ($arg) use ($message) {
  30. var_dump($arg . ' ' . $message);
  31. };
  32. $example("hello");
  33. ?>
批改老师:灭绝师太灭绝师太

批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系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+教程免费学