前言
PHP 函數參數可指定預設值,呼叫時省略該參數即自動使用預設值。本文涵蓋語法規則、常見陷阱、型別宣告結合、可變參數與實務設計模式。
基本語法
<?php
function capitalize(string $str, bool $each = true): string {
$str = strtolower($str);
if ($each) {
$str = ucwords($str);
} else {
$str = strtoupper($str);
}
return $str;
}
// 呼叫方式
echo capitalize("hEllo WoRld!"); // Hello World (使用預設 $each=true)
echo capitalize("hEllo WoRld!", false); // HELLO WORLD
echo capitalize("hEllo WoRld!", true); // Hello World
?>
語法規則與限制
| 規則 | 說明 | 範例 |
| 預設值必須是常數 | 不能是變數、函數呼叫、new 物件 | function foo($a = time()) ❌
function foo($a = 0) ✅ |
| 預設參數必須在非預設參數之後 | 定義順序:必填參數 → 選填參數 | function($a, $b = 1) ✅
function($a = 1, $b) ❌ |
| 可用陣列/常數作為預設值 | 陣列字面量、類別常數、define 常數 | function($a = [], $b = PHP_VERSION) ✅ |
| null 作為預設值 | 常用於可選參數 | function($a = null) ✅ |
型別宣告結合預設值(PHP 7.0+)
<?php
// 標量型別宣告 + 預設值
function process(string $name = 'Guest', int $age = 18, float $score = 0.0, bool $active = true): void {
// ...
}
// 可為 null 的型別(PHP 7.1+)
function findUser(int $id, ?string $defaultName = null): string {
// $defaultName 可為 string 或 null
return $defaultName ?? 'Unknown';
}
// 回傳型別宣告
function greet(string $name = 'World'): string {
return "Hello, $name!";
}
?>
經典陷阱:可變預設值(陣列/物件)
<?php
// ❌ 危險:預設值為陣列,所有呼叫共享同一陣列實例
function addItem(string $item, array $list = []): array {
$list[] = $item;
return $list;
}
$a = addItem('apple'); // ['apple']
$b = addItem('banana'); // ['apple', 'banana'] ❌ 預期 ['banana']
$c = addItem('cherry'); // ['apple', 'banana', 'cherry'] ❌
// ✅ 正確:預設值用 null,函數內部初始化
function addItemCorrect(string $item, ?array $list = null): array {
$list ??= []; // PHP 7.0+ null coalescing assignment
$list[] = $item;
return $list;
}
$a = addItemCorrect('apple'); // ['apple']
$b = addItemCorrect('banana'); // ['banana'] ✅
$c = addItemCorrect('cherry'); // ['cherry'] ✅
?>
進階模式
1. 選項陣列模式(Options Array)
<?php
function connect(string $dsn, array $options = []): PDO {
$defaults = [
'persistent' => false,
'timeout' => 30,
'charset' => 'utf8mb4',
'errmode' => PDO::ERRMODE_EXCEPTION,
];
$options = array_merge($defaults, $options);
$pdo = new PDO($dsn, $options['user'] ?? '', $options['pass'] ?? '', [
PDO::ATTR_PERSISTENT => $options['persistent'],
PDO::ATTR_TIMEOUT => $options['timeout'],
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$options['charset']}",
PDO::ATTR_ERRMODE => $options['errmode'],
]);
return $pdo;
}
// 使用:只覆蓋需要的選項
$pdo = connect('mysql:host=localhost;dbname=test', [
'user' => 'root',
'pass' => 'secret',
'timeout' => 60, // 覆蓋預設 30
]);
?>
2. 命名參數(PHP 8.0+)
<?php
function createUser(
string $email,
string $password,
string $role = 'user',
bool $emailVerified = false,
array $metadata = []
): User {
// ...
}
// PHP 8.0+ 可跳過中間參數直接指定後續參數
$user = createUser(
email: 'test@example.com',
password: 'secret',
emailVerified: true, // 直接指定第 4 參數,略過 $role
metadata: ['source' => 'api']
);
?>
3. 建構子屬性提升(PHP 8.0+)
<?php
class Config {
public function __construct(
public string $host = 'localhost',
public int $port = 3306,
public string $database = 'app',
public string $charset = 'utf8mb4',
public bool $ssl = false,
) {}
}
$config = new Config(port: 5432, database: 'prod');
?>
實務設計原則
- 預設值語意明確:
false/0/''/[] 皆有明確業務含義
- 避免可變預設值:永遠用
null + 函數內初始化
- 必要參數前置:必填參數在前,選填在後
- 布林旗標慎用:考慮用選項陣列或具名建構子替代多個布林參數
- 文件化預設行為:PHPDoc 註明預設值含義
反模式與修正
| 反模式 | 問題 | 修正 |
function($a = computeDefault()) | 語法錯誤 | function($a = null) { $a ??= computeDefault(); } |
function($a = [], $b) | 語法錯誤 | 調整順序 function($b, $a = []) |
function($flag = true) 多個布林 | 呼叫端易搞混順序 | 選項陣列或具名參數 |
| 預設值為新物件 | 共享實例、狀態洩漏 | function($obj = null) { $obj ??= new Class(); } |
總結
- 語法:
function name($param = defaultValue),預設值為常數運算式
- 順序:必填參數在前,選填參數在後
- 陷阱:陣列/物件預設值會被共享,**永遠用
null + ??= 初始化**
- 現代特性:PHP 7.0+ 型別宣告、PHP 7.1+ 可為 null、PHP 8.0+ 命名參數、建構子屬性提升
- 設計模式:選項陣列模式處理多選項、建構子提升簡化 DTO