函數是代碼復用核心。PHP 內建 1000+ 函數,但業務邏輯需自定義函數封裝。本文系統講解聲明語法、參數機制、返回類型、變量函數、匿名函數、箭頭函數、現代最佳實踐。
<?php
declare(strict_types=1); // 強制類型模式
// 完整聲明
function functionName(Type $param1, Type $param2 = 'default'): ReturnType {
// 函數體
return $result;
}
// 調用
$result = functionName('arg1', 'arg2');
function add(int $a, int $b): int {
return $a + $b;
}
&function swap(&$a, &$b): void {
[$a, $b] = [$b, $a];
}
$x = 1; $y = 2;
swap($x, $y); // $x=2, $y=1
function greet(string $name = 'Guest', string $greeting = 'Hello'): string {
return "$greeting, $name!";
}
// 必須在非默認參數右側
// function bad($a = 1, $b) {} // Fatal Error
... (5.6+)function sum(int ...$numbers): int {
return array_sum($numbers);
}
echo sum(1,2,3); // 6
echo sum(...[4,5]); // 9 (解包數組)
function createUser(string $name, int $age = 18, string $role = 'user'): array {
return compact('name', 'age', 'role');
}
$user = createUser(name: 'Alice', role: 'admin'); // 跳過 age
| 類型 | 語法 | 說明 |
|---|---|---|
| 標量 | function f(): int | int/float/string/bool |
| 數組 | function f(): array | |
| 對象/介面 | function f(): User | |
| 可空 | function f(): ?User | ?Type = Type|null |
| void | function f(): void | 不可返回值,或 return; |
| never | function f(): never | 8.1+,永不返回(拋異常/死循環/exit) |
| mixed | function f(): mixed | 8.0+,任意類型 |
| iterable | function f(): iterable | 7.1+,array|Traversable |
function stats(array $data): array {
return [
'sum' => array_sum($data),
'avg' => array_sum($data) / count($data),
'max' => max($data),
];
}
['sum' => $s, 'avg' => $a] = stats([1,2,3]); // 解構賦值 7.1+
readonly class Stats {
public function __construct(
public float $sum,
public float $avg,
public float $max,
) {}
}
function stats(array $data): Stats {
return new Stats(
array_sum($data),
array_sum($data) / count($data),
max($data)
);
}
$stats = stats([1,2,3]);
echo $stats->avg;
function readLargeFile(string $path): Generator {
$fp = fopen($path, 'r');
while (($line = fgets($fp)) !== false) {
yield trim($line);
}
fclose($fp);
}
foreach (readLargeFile('huge.log') as $line) {
// 逐行處理,內存常數級
}
$multiply = function(int $a, int $b): int {
return $a * $b;
};
echo $multiply(3, 4); // 12
// 綁定外部變量(use)
$factor = 10;
$scale = function(int $x) use ($factor): int {
return $x * $factor;
};
// 引用綁定(可修改外部)
$counter = 0;
$inc = function() use (&$counter): int {
return ++$counter;
};
$x * $factor;
echo $scale(5); // 50
// 多行箭頭函數 (8.1+)
$complex = fn($x) => match (true) {
$x > 0 => 'positive',
$x < 0 => 'negative',
default => 'zero',
};
<?php
function foo() { echo 'foo'; }
$func = 'foo';
$func(); // 調用 foo()
// callable 類型聲明 (8.0+)
function execute(callable $callback, mixed ...$args): mixed {
return $callback(...$args);
}
execute('strlen', 'hello'); // 5
execute([$obj, 'method'], $arg);
execute(fn($x) => $x * 2, 5); // 10
// Closure::fromCallable (7.1+)
$cl = Closure::fromCallable('strlen');
$cl('test'); // 4
declare(strict_types=1),全項目統一。throw new DomainException() 而非返回 false/-1。@param @return @throws @deprecated,配合 PHPStan/Psalm。