变量与函数的声明
发布于:2022-04-20 14:09:02
次阅读
变量的声明
//使用 $ 符声明变量$user = '新手1314';//使用echo 输出声明的变量echo $user;//输出结果:新手1314
函数的声明
//PHP函数的声明与js的函数声明一致,但是可以限定参数与返回值的类型function getUser(string $user): string{ return 'Hello,'.$user;}//调用,与js一致echo getUser('新手1314');//输出结果:Hello,新手1314
当参数不足时,设置默认值
function getMoney(float $price,int $num = 1):float{ return $price * $num;}echo '总金额为'. getMoney(35.6).'元 <br>';echo '总金额为'. getMoney(35.6,10).'元';//输出结果分别为:总金额为35.6元,总金额为356元
声明一个匿名函数
$get = function(float $price , int $num = 1):float{ return $price * $num;};echo "总金额为 {$get(35.6)} 元<br>";//双引号输出echo '总金额为'.$get(35.6).'元';//单引号输出//两者输出结果一致:总金额为35.6 元
参数过多时,设置一个数组:…
$sum = function(...$arr){ return array_reduce($arr,function($acc,$cur){ reutrn $acc + $cur; },0);};echo $sum(1,2,3,4,5);//输出结果为:15