Correcting teacher:Guanhui
Correction status:qualified
Teacher's comments:写的还行!小驼峰命名法开头是不能大写的!
无参函数示例:
function Fun(参数、参数、参数.....)
{
函数体可执行的代码;
}
function Fun()
{
echo "欢迎您来到php函数的世界!";
}
function kd(float $zl,int $mdd):float
{
$zl = ceil($zl);
switch($mdd)
{
case 1:
$qb = 10;
$xz = 5;
break;
case 2;
$qb = 10;
$xz = 8;
break;
case 3;
$qb = 15;
$xz = 10;
break;
}
$yf = $qb + $xz*($zl-1);
return $yf;
}
echo kd(7.2,2);
<?php
function Fun()
{
echo "欢迎您来到php函数的世界!";
}
echo "echo调用:";
echo fun();
echo "<br>";
$hello=Fun();
echo $hello;
示例
//可变函数
//对自定义函数的函数名赋值后调用。
echo "<b>可变函数</b>";
echo "<br>";
$f = 'yf';
echo "您购买的活动实付金额是:¥".$f(6.5,1.3);
echo "<hr>";
echo "<b>匿名函数</b>";
echo "<br>";
$yh = 0.8; //使用use调用外面变量
$func = function(float $zl,float $dj) use ($yh):float
{
$je = $zl * $dj;
echo "您购买的金额是:¥".$je."<br>";
if($zl>5)
{
$je = $je * $yh;
}
return $je;
}; //以为是给变量赋值所有这里必须要打;
echo "您购买的活动实付金额是:¥".$func(6.5,1.3);
echo "<hr>";
echo "<b>父作用域函数</b>";
echo "<br>";
$j = function ($yh)
{
$func = function(float $zl,float $dj) use ($yh):float
{
$je = $zl * $dj;
echo "您购买的金额是:¥".$je."<br>";
if($zl>5)
{
$je = $je * $yh;
}
return $je;
};
return $func;
};
echo "您购买的活动实付金额是:¥".$j(0.7)(6.5,2.1);
对函数的记住类型进行的编写,加深对函数的认识。
示例图
1.函数必须有返回值:
function a()
{
}
echo a();
2.函数返回单一的值
function a()
{
echo "函数返回值";
}
echo a();
echo "<br>";
function b(int $c):int
{
$c = $c/2;
return $c;
}
echo b(100);
3.函数字符串返回
function c():string
{
$lx = "利息";
$bj = "本金";
$yh = "月还";
return $bj.",".$lx.",".$yh;
}
echo c();
4.函数数组返回
function d(float $dk,int $n,float $l):array
{
$nx = $dk * $l * $n;
$xh = $dk + $nx;
$yh = $xh / ($n * 12);
return ["nx"=>$nx,"xh"=>$xh,"yh"=>$yh];
}
$myh=(d(400000,20,0.047)['yh']);
$myh =number_format($myh,2);
echo $myh;
5.通过josn返回
function e():string
{
$gj ="中国";
$sf ="贵州省";
$cs ="贵阳市";
return json_encode(["gj"=>$gj,"sf"=>$sf,"cs"=>$cs]);
}
echo e();
echo "<br>";
$bb=json_decode(e());
foreach($bb as $k => $value)
{
echo $k ."=>". $value;
}
6.通过序列化返回
function f()
{
$gj ="中国";
$sf ="贵州省";
$cs ="贵阳市";
return serialize(["gj"=>$gj,"sf"=>$sf,"cs"=>$cs]);
}
echo f();
echo "<br>";
$dm = unserialize(f());
foreach($dm as $key => $value)
{
echo $key."=>".$value;
}
function a(int $b): int
{
$b= $b*2;
return $b;
}
echo a(15);
function c(float $d): float
{
$d = $d * 3;
return $d;
}
$e = 12;
echo c($e);
//100内能整除4的数的和
$d = 0;
function js(int $a,int $b=4):int
{
for($i=1;$i<=$a;$i++)
{
if($i % $b == 0)
{
global $d;
$d = $d + $i;
}
}
return $d;
}
echo js(100);
function sy(...$sz)
{
return $sz;
}
$res =sy(1,2,3,4,5,6,7,8,9,10);
$sy1 = [1,2,3,4,5,6,7,8,9,10];
//print_r($res);
echo "<br>";
$res1 = sy(...$sy1);
print_r($res1);
两种方法对剩余参数进行调用,关键使用…来替换参数。
没有传送的参数,必须写到传送参数的后面
示例
<?php
namespace de {
function demo1()
{
return __FUNCTION__;
}
}
namespace de1{
function demo1() {
return __FUNCTION__;
}
}
namespace{
echo de\demo1();
echo "<br>";
echo de1\demo1();
}
对两个命名空间的访问,