Blogger Information
Blog 12
fans 0
comment 0
visits 6520
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
函数的返回值和参数,匿名函数和变量的作用域
Giesen?
Original
468 people have browsed it
  1. // 只会返回一个return 且第一个return后面代码不会执行
  2. function demo()
  3. {
  4. return sha1('wwwphpxnccsdsds');
  5. return md5('wwwphpcn');
  6. return 1==1;
  7. return new StdClass;
  8. return array('12','45');
  9. return 88.88;
  10. return 'nihao';
  11. return true;
  12. }
  13. echo '<hr>';
  14. var_dump(demo());
  15. // 多值返回
  16. // 数组
  17. function arr(){
  18. return ['status'=>1,'msg'=>'登录成功'];
  19. }
  20. echo '<hr>';
  21. print_r(arr());
  22. // 对象
  23. function demo2()
  24. {
  25. return new class()
  26. {
  27. public $name = 'chloe';
  28. public $gender = '女';
  29. };
  30. }
  31. $obj = demo2();
  32. var_dump($obj);echo '<hr>';
  33. echo $obj->name;
  34. echo $obj->gender;
  35. echo '<hr>';
  36. // 参数
  37. function mx($name){
  38. echo $name;
  39. }
  40. mx('刘星');
  41. // 封装函数
  42. // 编写代码时 将需要随时更改的变量 由函数的参数进行传入 方便代码的调试和修改
  43. // 函数的参数可以设置默认的参数 建议 默认参数设置在最右边
  44. function createTable(int $rows,int $cols,string $content,string $bgColor=blue) :string
  45. {
  46. $table = "<table border ='1' cellspacing='0' bgColor='$bgColor'>";
  47. for ($i=0; $i < $rows; $i++) {
  48. $table .= "<tr>";
  49. for ($j=0; $j < $cols ; $j++) {
  50. $table .= "<td>$content</td>";
  51. }
  52. $table .= "</tr>";
  53. }
  54. $table .= '</table>';
  55. return $table;
  56. }
  57. echo createTable(4,3,'你好','red');
  58. // 匿名函数
  59. // 临时创建的一个没有名字的函数
  60. // 命名函数可以全局识别 匿名函数不能
  61. $closure = function($name){
  62. return "欢迎{$name}来到php中文网做客<br>";
  63. };
  64. echo $closure('胡歌');
  65. // 变量作用域
  66. // 函数外部变量可以通过参数形式传入内部
  67. // 全局变量如果想在自定义函数内部使用则必须使用 global /$GLOBALS关键字声明
  68. // 自定义函数内部变量在退出声明变量的函数时,变量和值会被清除
  69. $one = 200;
  70. $two = 300;
  71. $itemName = 'iphone 12 pro max 256g';
  72. $itemPrice = 12585;
  73. function add(int $a,int $b):string
  74. {
  75. return $a+$b;
  76. }
  77. // var_dump(add(1,2));
  78. var_dump(add($one,$two));
  79. function getItemInfo_pro()
  80. {
  81. // global $itemPrice,$itemName;
  82. return sprintf('今日主推产品:%s, 商品价格: %d<br>',$GLOBALS['itemName'],$GLOBALS['itemPrice']);
  83. }
  84. echo getItemInfo_pro();
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!