函数
封装一段用于完成特定功能的代码。
通俗理解函数:可以完成某个工作的代码块,就像小朋友搭房子用的积木一样,可以反复使用,在使用的时候,拿来即用,而不用考虑它的内部构成。
函数分类:①内置函数(字符串操作函数、数组操作函数)②自定义函数。
内置函数
$str = 'ABcd';
$upper = strtoupper($str); // 调用strtoupper()函数将$str转换成大写
$lower = strtolower($str); // 调用strtolower()函数将$str转换成小写
echo $upper; // 输出结果:ABCD
echo $lower; // 输出结果:abcd
自定义函数
函数语法
function 函数名([参数1, 参数2, ……])
{
函数体……
}
函数的定义由以下4部分组成:
关键字function
函数名functionName
参数
函数体
参数设置
无参数
function shout()
{
return 'come on';
}
echo shout();// 输出结果:come on
带参数
function add($a, $b)
{
$a = $a + $b;
return $a;
}
add(5,6);
引用传参
;
function extra(&$str)
{
$str .= ' and some extra';
}
$var = 'food';
extra($var);
// 输出结果:food and some extra
echo $var
默认参数
function say($p, $con = 'say "Hello"')
{
return "$p $con";
}
// 输出结果:Tom say "Hello"
echo say('Tom');
指定参数类型(弱)
function sum1(int $a, int $b)
{
return $a + $b;
}
echo sum1(2.6, 3.8); // 输出结果:5
指定参数(强)
declare(strict_types = 1);
function sum2(int $a, int $b)
{
return $a + $b;
}
echo sum2(2.6, 3.8); // 输出结果:Fatal error: .....