PHP 函数

Defining and calling, defaults, variadics, return types, closures and arrow functions.

Beginner
Key PointsFunction names are case-insensitive; parameters support defaults, type declarations and references.

定义与调用

PHP
<?php
function add(int $a, int $b = 10): int {
    return $a + $b;
}

echo add(1, 2), " ", add(1), "\n";
echo ADD(1, 2), "\n";       // 函数名不区分大小写

function greet(string $name): string {
    return "你好,$name";
}
echo greet("Tom"), "\n";
Output
3 11
3
你好,Tom
Function names are case-insensitive but variables are not. Redeclaring a function is a fatal error — the classic collision when pulling in libraries.

参数

PHP
<?php
// 默认值
function price(float $amount, float $rate = 0.13): float {
    return $amount * (1 + $rate);
}
echo price(100), "\n";         // 113
echo price(100, 0.06), "\n";   // 106

// 命名参数(PHP 8)
echo price(rate: 0.06, amount: 200), "\n";   // 212

// 可变参数
function sum(int ...$nums): int {
    return array_sum($nums);
}
echo sum(1, 2, 3, 4), "\n";    // 10

// 展开数组传参
$args = [5, 6, 7];
echo sum(...$args), "\n";      // 18

// 引用传递
function swap(int &$a, int &$b): void {
    [$a, $b] = [$b, $a];
}
$x = 1; $y = 2;
swap($x, $y);
echo "$x $y\n";                // 2 1
Output
113
106
212
10
18
2 1

Defaults must be constant expressions — function f($a = time()) is illegal. Pass null and fall back inside the body.

Return values

PHP
<?php
function divide(float $a, float $b): float {
    if ($b == 0.0) {
        throw new InvalidArgumentException("除数不能为 0");
    }
    return $a / $b;
}

echo divide(10, 4), "\n";

// 返回多值用数组
function minMax(array $nums): array {
    return [min($nums), max($nums)];
}
[$lo, $hi] = minMax([3, 1, 4, 1, 5]);
echo "$lo $hi\n";

// 无返回值
function logMsg(string $msg): void {
    echo "[LOG] $msg\n";
}
logMsg("done");
Output
2.5
1 5
[LOG] done

A function without return yields null. Declaring : void states the intent and helps static analysis.

Static variables

A static variable persists across calls and initialises only once.

PHP
<?php
function counter(): int {
    static $n = 0;
    return ++$n;
}

echo counter(), counter(), counter(), "\n";

function fib(int $n): int {
    static $cache = [];
    if ($n < 2) return $n;
    return $cache[$n] ??= fib($n - 1) + fib($n - 2);
}
echo fib(30), "\n";
Output
123
832040

??= (PHP 7.4) assigns only when unset — perfect for memoisation.

Closures and arrow functions

PHP
<?php
$factor = 3;

// 匿名函数必须 use 才能拿到外部变量
$mul = function ($n) use ($factor) {
    return $n * $factor;
};
echo $mul(4), "\n";          // 12

// 箭头函数自动捕获(按值)
$double = fn($n) => $n * 2;
echo $double(5), "\n";       // 10

// 按引用捕获,闭包内改外部变量
$count = 0;
$inc = function () use (&$count) {
    $count++;
};
$inc(); $inc();
echo $count, "\n";           // 2
Output
12
10
2
Featurefunction () use ()fn() =>
Auto capture否,必须 use是
Capture by reference支持 use (&$x)不支持
Multi-statement body支持只支持单个表达式
Since5.37.4

Type declarations and strict mode

PHP coerces by default: passing "3" to int $a becomes 3. Add declare(strict_types=1); at the top of the file to get a TypeError instead.

PHP
<?php
declare(strict_types=1);

function twice(int $n): int {
    return $n * 2;
}

echo twice(5), "\n";

try {
    echo twice("5");
} catch (TypeError $e) {
    echo "类型错误: " . $e->getMessage(), "\n";
}
Output
10
类型错误: twice(): Argument #1 ($n) must be of type int, string given
strict_types applies per file and only to the calling side. A library declaring it does not make its callers strict.

Friends & Partners