批改状态:合格
老师批语:以于参数与返回值的理解不错
全局定义三个函数, 本博文的示例调用时说明略.
function echobr($param = ''){echo $param . '<br>';}function dumpbr($param = ''){var_dump($param);echo '<br>';}function printfpre($param = ''){printf('<pre>%s</pre>', print_r($param, true));}
函数定义格式
function 函数名[可选](参数列表[可选]) : 返回值类型[可选] {函数体...return 返回值/变量/...[可选]}
函数定义demo:
<?php/*打招呼函数*/function sayHello($name) : string {return $name . ', 你好!';}// 调用函数$str = sayHello();echobr($str);
函数可分为以下四种类型
自定义函数
sayHello()函数就是自定义函数示例
<?phpfunction info($name, $salary) : string {$info = $name . '本月的薪水是: ' . $salary . '元';echobr($info);}info('zhangsan', 8000);
系统函数
is_null(), empty(), gettype(), is_array()等可变函数
示例
<?phpfunction add(int $num1, int $num2) : int {echobr($num1 + $num2);}function minus(int $num1, int $num2) : int {echobr($num1 - $num2);}$funcName = 'add';$funcName(5, 8);$funcName = 'minus';$funcName(20, 10);
匿名函数
示例1:
<?php// 计算梯形的面积function calcArea($topLength, $bottomLength, $height, $add) {// 上底加下底$totalLength = $add($topLength, $bottomLength);// 乘以高除以二$s = $totalLength * $height / 2;return $s;}echobr(calcArea(3, 7, 5, function($a, $b){return $a + $b;}));/*执行结果:25*/
示例2:
// 计算图形面积function calcArea1($figure){if ($figure === '三角形') {return function ($bottom, $height) {// 底乘以高除以二return $bottom * $height / 2;};}if ($figure === '圆形') {return function ($r) {if (!defined('PI')) {define('PI', 3.14);}/* π乘以半径的平方 */return PI * $r ** 2;};}if ($figure === '矩形') {return function ($long, $height) {// 长乘以宽return $long * $height;};}return '暂无法计算此图形的面积';}$func = calcArea1('三角形');if(gettype($func) === 'object') {echobr($func(4, 8));} else {echobr($func);}/*执行结果:16*/
函数的返回值为单值
return的是显式返回;示例略.return的, 遇到}也会返回, 默认返回null.
// 没有return的函数function sayHello() {echobr('hello');}$data = sayHello();dumpbr($data);/*运行结果:helloNULL*/
若要返回多值, 返回值有以下四种处理方式
字符串拼接
字符串拼接的使用场景
示例
<?phpfunction userInfo() {$username = 'zhangsan';$sex = 'male';$age = '24';$salary = 8000;return $username . ',' . $sex . ',' . $age . ',' . $salary;}$userInfo = userInfo();$userArray = explode(',', $userInfo);dumpbr($userArray);/*执行结果:array(4) { [0]=> string(8) "zhangsan" [1]=> string(4) "male" [2]=> string(2) "24" [3]=> string(4) "8000" }*/
返回数组
function productList() {$productList = [['id' => 1,'cat_id' => 1,'name' => '华为P40','brand' => '华为'],['id' => 2,'cat_id' => 1,'name' => '华为Mate30','brand' => '华为'],['id' => 1,'cat_id' => 1,'name' => 'Apple 11 Pro Max','brand' => 'Apple']];return $productList;}printf('<pre>%s</pre>', print_r(productList(), true));/*允许结果:Array([0] => Array([id] => 1[cat_id] => 1[name] => 华为P40[brand] => 华为)[1] => Array([id] => 2[cat_id] => 1[name] => 华为Mate30[brand] => 华为)[2] => Array([id] => 1[cat_id] => 1[name] => Apple 11 Pro Max[brand] => Apple))*/
function productList() {$productList = [['id' => 1,'cat_id' => 1,'name' => '华为P40','brand' => '华为'],['id' => 2,'cat_id' => 1,'name' => '华为Mate30','brand' => '华为'],['id' => 1,'cat_id' => 1,'name' => 'Apple 11 Pro Max','brand' => 'Apple']];return json_encode($productList);}printf('<pre>%s</pre>', productList());/*运行结果[{"id":1,"cat_id":1,"name":"\u534e\u4e3aP40","brand":"\u534e\u4e3a"},{"id":2,"cat_id":1,"name":"\u534e\u4e3aMate30","brand":"\u534e\u4e3a"},{"id":1,"cat_id":1,"name":"Apple 11 Pro Max","brand":"Apple"}]*/
和json数据类似,序列化的结果,也是有一定规则的字符串。
function productList() {$productList = [['id' => 1,'cat_id' => 1,'name' => '华为P40','brand' => '华为'],['id' => 2,'cat_id' => 1,'name' => '华为Mate30','brand' => '华为'],['id' => 1,'cat_id' => 1,'name' => 'Apple 11 Pro Max','brand' => 'Apple']];return serialize($productList);}printf('<pre>%s</pre>', productList());/*运行结果:a:3:{i:0;a:4:{s:2:"id";i:1;s:6:"cat_id";i:1;s:4:"name";s:9:"华为P40";s:5:"brand";s:6:"华为";}i:1;a:4:{s:2:"id";i:2;s:6:"cat_id";i:1;s:4:"name";s:12:"华为Mate30";s:5:"brand";s:6:"华为";}i:2;a:4:{s:2:"id";i:1;s:6:"cat_id";i:1;s:4:"name";s:16:"Apple 11 Pro Max";s:5:"brand";s:5:"Apple";}}*/
值参数
值参数只传递参数值, 原变量的值保持不变, 不受函数处理的影响
示例:
$name = 'zhangsan';function sayHello($username) {$username .= ', 你好';echobr($username);}sayHello($name);/* 全局变量$name的值还是'zhangsan' */echobr($name);/*运行结果:zhangsan, 你好zhangsan*/
引用参数
$num = 0;// 原值+5;function addFive(&$num) {$num += 5;}addFive($num);echobr($num);/*运行结果:5*/
默认参数
1.和2.都属于必选参数, 默认参数是可选参数, 可选参数必须放在必选参数后面
就是给形参加默认值,调用函数时,若不给该参数传入实参,则该形参就初始化为默认值。
// 循环生成key=value的数组function createArrayVal($start, $length, $arr = []) {for($index = 0; $index < $length; $index++) {$sum = $start + $index;$arr[$sum] = $sum;}return $arr;}// 先生成5个数组元素$arr = createArrayVal(0, 5);printfpre($arr);// 再生成3个数组元素printfpre(5, 3, $arr);/*运行结果:Array([0] => 0[1] => 1[2] => 2[3] => 3[4] => 4)Array([0] => 0[1] => 1[2] => 2[3] => 3[4] => 4[5] => 5[6] => 6[7] => 7)*/
个人理解就是,如果一个函数设置了剩余参数,那么传入的参数数量比函数的参数多时,多出的那部分参数当作数组的元素传入到剩余参数中。
function register($first, $second, $third, $fourth, ...$more) {echobr('第一个挂号的是:' . $first);echobr('第二个挂号的是:' . $second);echobr('第三个挂号的是:' . $third);echobr('第四个挂号的是:' . $fourth);eochobr('今天加号有' . count($more) . '名病人。它们分别是:');foreach($more as $key => $item) {echobr("第{$key + 1}个加号的是:{$item}");}}register('zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'Lucy', 'Lily', 'lilei');/*运行结果:第一个挂号的是:zhangsan第二个挂号的是:lisi第三个挂号的是:wangwu第四个挂号的是:zhaoliu今天加号有3名病人。它们分别是:第1个加号的是:Lucy第2个加号的是:Lily第3个加号的是:lilei*/
剩余参数(数组),也可以作为实参传入函数中,这样数组中的元素值,就会按顺序赋值给函数的参数
function register($username, $password, $repassword, $age) {echobr("注册成功,注册信息为:");echobr("用户名:{$username}");echobr("密码:{$password}");echobr("年龄:{$age}");}$user = ['admin', '123456', 25];register(...$user);/*执行结果:注册成功,注册信息为:用户名:admin密码:123456年龄:25*/
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号