函式是程式碼復用、模組化與可測試性的基石。PHP 從早期簡單的 function name() 演進至今,已支援型別宣告、回傳型別、可變參數、箭頭函式、一級可呼叫物件等現代特性。本文系統整理函式宣告語法、參數機制、變數作用域、回調模式、內部函式與實戰規範,助你寫出健壯、可維護的函式。
<?php
// 完整型別宣告版本
function calculateTotal(
array $items, // 陣列型別
float $taxRate = 0.05, // 預設值 + 型別
callable $formatter = null // 可呼叫型別
): float { // 回傳型別
$subtotal = array_reduce($items, fn($sum, $item) => $sum + $item['price'] * $item['qty'], 0);
$total = $subtotal * (1 + $taxRate);
return $formatter ? $formatter($total) : $total;
}
// 呼叫
$items = [
['price' => 100, 'qty' => 2],
['price' => 50, 'qty' => 3],
];
echo calculateTotal($items); // 367.5
echo calculateTotal($items, 0.1, fn($v) => '$' . number_format($v, 2)); // $407.00
?>
new Class())。<?php
function byValue($x) { $x += 10; }
function byRef(&$x) { $x += 10; }
$a = 1; byValue($a); echo $a; // 1
$b = 1; byRef($b); echo $b; // 11
?>
&(僅宣告處需標示,呼叫處 PHP 5.4+ 不需加)。...(PHP 5.6+)<?php
function sum(float ...$numbers): float {
return array_sum($numbers);
}
echo sum(1, 2, 3.5); // 6.5
// 解包陣列當參數
$vals = [10, 20, 30];
echo sum(...$vals); // 60
?>
<?php
function createUser(string $name, int $age = 18, string $role = 'member') { /* ... */ }
createUser(name: 'Alice', role: 'admin'); // 順序任意、略過預設值
?>
| 類型 | 存活週期 | 可見範圍 | 關鍵字 |
|---|---|---|---|
| 區域變數 | 函式執行期間 | 僅函式內部 | — |
| 全域變數 | 腳本執行期間 | 全域(需 global 或 $GLOBALS) | global / $GLOBALS |
| 靜態變數 | 腳本執行期間 | 僅函式/方法內部 | static |
| 超全域變數 | 請求期間 | 任何位置 | $GLOBALS, $_GET, $_POST... |
<?php
function counter() {
static $count = 0; // 僅初始化一次
return ++$count;
}
echo counter(); // 1
echo counter(); // 2
echo counter(); // 3
// 遞迴計算費波那契(備忘錄模式)
function fib(int $n): int {
static $cache = [0 => 0, 1 => 1];
return $cache[$n] ??= fib($n - 1) + fib($n - 2);
}
echo fib(20); // 6765
?>
<?php
function apply(array $data, callable $callback): array {
return array_map($callback, $data);
}
$numbers = [1, 2, 3, 4];
$squared = apply($numbers, function($n) { return $n * $n; });
print_r($squared); // [1, 4, 9, 16]
// 類方法回調
class Processor {
public function double($n) { return $n * 2; }
}
$proc = new Processor();
$doubled = apply($numbers, [$proc, 'double']);
// 或靜態方法
$doubled = apply($numbers, ['Processor', 'double']);
?>
...(PHP 8.1+)<?php
$callback = strlen(...); // 直接取得 Closure
$callback = $proc->double(...); // 實例方法
$callback = Processor::double(...); // 靜態方法
// 等同於
$callback = fn($arg) => strlen($arg);
// 但更簡潔、效能略優、支援反射取得原函式資訊
?>
array_map(), array_filter(), array_reduce(), array_walk()usort(), uksort(), uasort()call_user_func(), call_user_func_array()(動態呼叫)preg_replace_callback()<?php
/**
* 計算訂單總價(含稅)
*
* @param array $items 訂單明細
* @param float $taxRate 稅率 (預設 5%)
* @param callable(float): string|null $formatter 格式化器
* @return float|string 總價或格式化字串
* @throws InvalidArgumentException 當項目為空
*/
function calculateTotal(array $items, float $taxRate = 0.05, callable $formatter = null): float|string {
if (empty($items)) {
throw new InvalidArgumentException('訂單明細不可為空');
}
// ...
}
?>
PHP 8.0+ 建議改用 Attributes:
<?php
#[ReturnTypeWillChange] // 兼容舊版
function calculateTotal(...): float|string { /* ... */ }
?>
<?php
function outer($x) {
function inner($y) { // 定義在全域命名空間!
return $y * 2;
}
return inner($x) + 10;
}
echo outer(5); // 20
// 內部函式實際是全域函式,第二次呼叫 outer() 會重複定義報錯
?>
建議改用閉包:
$inner = fn($y) => $y * 2; // 箭頭函式(PHP 7.4+)
// 或
$inner = function($y) { return $y * 2; };
use 父作用域變數(自動按值捕獲)。return。& 傳址捕獲(需用完整閉包)。func_get_args() 等動態特性:阻礙靜態分析與 JIT 優化。callable 型別提示:而非 Closure,支援更廣(函式名、陣列、物件、箭頭函式)。false/null 混淆正常值。掌握 PHP 函式的完整特性——從參數傳遞、作用域、回調模式到現代型別系統——能讓你設計出低耦合、高內聚、可測試的程式碼。下次寫 function 時,試著問自己:「型別加了嗎?單一職責嗎?能不能用箭頭函式簡化?」