Blogger Information
Blog 14
fans 0
comment 0
visits 9499
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP返回值&参数&变量作用域
Mr.Ran
Original
536 people have browsed it

函数返回值

函数体内通过 return 语句将值返回,只能返回单个值,可以返回包括数组和对象的任意类型,return后面的代码不会被执行。

返回单个值:

  1. <?php
  2. function getPrice()
  3. {
  4. return 48.22;
  5. }
  6. printf("今天的猪肉价格是:%s元/斤",getPrice());
  7. ?>

返回数组(多个值):

  1. <?php
  2. function getUserInfo(){
  3. $uinfo = ['uname'=>'root','pwd'=>'123456'];
  4. return $uinfo;
  5. }
  6. print_r(getUserInfo());
  7. ?>

函数的参数

参数为函数的调用者提供一个接口去改变函数体的执行行为,没有参数,函数执的执行任务是固定的,参数可以多个,以“,”分隔。

  1. <?php
  2. //两个数合计函数
  3. function sum($a,$b)
  4. {
  5. return $a + $b;
  6. }
  7. echo '合计:'.sum(22,11);
  8. ?>

输出结果:33

变量作用域

变量作用域即它定义的生效范围,分局部变量和全局变量,全局变量使用 global 声明。

  1. <?php
  2. $a = 0;
  3. function price(){
  4. //将$a在函数体内声明全局变量
  5. global $a;
  6. $a = 1000;
  7. }
  8. price();
  9. echo $a;
  10. ?>
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