函數是程式碼重複使用的基本單位。本章詳細說明 PHP 函數的定義、參數傳遞(傳值/傳址)、回傳值、預設參數、變數作用域與全域變數,並附上實務範例。
<?php
// 定義:接收兩個參數,回傳相加結果
function myAdd($a, $b) {
$sum = $a + $b;
return $sum; // 回傳結果給呼叫者
}
// 呼叫:將回傳值指派給變數
$result = myAdd(59, 100);
echo $result; // 輸出 159
?>
在參數前加 & 表示傳址,函數內修改會影響外部原變數:
<?php
function appendString(&$str) {
$str .= ' 也喜歡藍色。';
}
$text = '喜歡紅色,';
appendString($text);
echo $text; // 輸出:喜歡紅色,也喜歡藍色。
?>
參數可指定預設值,呼叫時可省略:
<?php
function myColor($color = '藍色') {
return "我喜歡的顏色:{$color}";
}
echo myColor(); // 輸出:我喜歡的顏色:藍色
echo myColor('粉色'); // 輸出:我喜歡的顏色:粉色
?>
函數內預設為區域作用域,需用 global 存取全域變數:
<?php
$a = 1;
$b = 2;
function sum() {
global $a, $b; // 宣告使用全域變數
$b = $a + $b; // 修改全域 $b
}
sum();
echo $b; // 輸出 3
?>
<?php
function square($num) {
return $num * $num;
}
echo square(4); // 輸出 16
echo square(7); // 輸出 49
?>
<?php
// 使用 ... 運算子接收不定數量參數
function sumAll(...$numbers) {
$total = 0;
foreach ($numbers as $n) {
$total += $n;
}
return $total;
}
echo sumAll(1, 2, 3); // 6
echo sumAll(10, 20, 30, 40); // 100
// 陣列展開傳遞
$arr = [5, 10, 15];
echo sumAll(...$arr); // 30
?>
calculateTotal() 優於 func1()function add(int $a, int $b): intdeclare(strict_types=1);| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
| function test($a=1, $b) | 預設參數必須在非預設參數之後 | function test($b, $a=1) |
| function &getRef() { return $x; } | 回傳傳址需回傳變數,非運算結果 | function &getRef() { return $this->prop; } |
| $x = 1; function foo() { echo $x; } | 函數內無法直接存取外部變數 | global $x; 或傳參數 function foo($x) |
| return $a + $b; | 忘記 return,函數回傳 null | 確認所有路徑都有 return |