PHP 函数
function functionName($param1, $param2, ...) {
}
- 以关键字 function 开头
- 函数名字大小写不敏感
- 参数可以有默认值
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<title>Function</title>
</head>
<body>
<div class="well">
<?php
function greet($greetings = 'Hello world!', $count = 1) {
for ($i = 0; $i < $count; ++$i) {
echo "$greetings<br>";
}
}
greet();
greet('Hi, there!');
greet('PHP is good!', 3);
?>
</div>
</body>
</html>
查看运行结果
传递引用参数
- 在参数前加 & 表示传递引用
- 传递引用可以通过改变形参的值来改变实参
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<title>Pass By Reference</title>
</head>
<body>
<div class="well">
<?php
function passByValue($x) {
++$x;
}
echo "<h2>Pass By Value</h2>";
$x = 5;
echo "origin x: $x<br>";
passByValue($x);
echo "after call passByValue(), x: $x<br>";
function passByReference(&$x) {
++$x;
}
echo "<h2>Pass By Reference</h2>";
$x = 5;
echo "origin x: $x<br>";
passByReference($x);
echo "after call passByReference(), x: $x<br>";
?>
</div>
</body>
</html>
查看运行结果