批改状态:合格
老师批语:你用得是在线编辑器吗? 建议用本地的, 后面的教学对版本是有要求的
函数是实现代码复用的重要方法,可直接在需要的地方直接调用。
函数有4种类型:自定义函数,系统函数,可变函数,匿名函数。
自定义函数:function del(){…}|自己定义一个del()函数
演示:
<?php
function del($a,$b)
{
return $a*$b;
}
echo del(10,20);
输出结果:
```
系统函数:printf(),count()|系统预定义的函数,不同function声明,直接调用就可以使用
演示:
<?php
function del($a,$b)
{
return $a*$b;
}
printf(del(10,20));//printf()是系统预定义的函数,可以直接打印输出函数内内容//
输出结果:
<?phpfunction del(float $a, float $b):float{return $a/$b;}$del = 'del';echo '湖人队的胜率是'.$del(62,82);
输出结果:
匿名函数:$money=function (){….}|其实就是闭包函数,主要是用于回调处理
演示:根据赛前预测的概率,判断出湖人队的胜率,来计算出本赛季夺冠的概率
<?php$key=function ($res){return function (float $a,float $b)use($res){$k=($a/$b)*$res;return '湖人队的夺冠率是'.$k;};};echo $key(0.9)(62,82);

个人理解:,如果父作用域是一个函数,子函数要先return,不然会报错。
原则上函数的返回是单值,由于其他的需要,往往需要多值。
<?phpfunction dome():string{$status=0;$res='退出';return '用户的状态是' .$status .':'. $res;}echo dome();
输出结果:
<?phpfunction demo2() : array{return ['status'=>1, 'message'=>'成功'];}$res=print_r(demo2(),true);printf('<pre>%s</pre>',$res);echo demo2()['status']==1?'用户付款'.demo2()['message']:'失败';
输出结果:
演示:判断$status来判断付款的状态
<?phpfunction demo3() : string{return json_encode(['status'=>1,'message'=>'成功']);}$data= demo3();$var=json_decode($data,true);if($var['status']){echo '用户付款'.$var['message'];}else{echo '用户付款失败';}
输出结果:
注意点:json_encode()函数对变量进行 utf—8 编码|json_decode()函数将json数据还原
演示:判断$status来判断付款的状态
<?phpfunction demo4() : string{return serialize(['status'=>1,'message'=>'成功']);}echo demo4();echo '<hr>';$data=unserialize(demo4());if($data['status']==1){echo '用户付款'.$data['message'];}else{echo '用户付款失败!';}
输出结果:
注意点:serialize()函数用来序列化一个数组,unserialize()用来反序列对象
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号