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>
查看運行結果