箭头函数 #
一、箭头函数基础 #
1.1 什么是箭头函数 #
PHP 7.4引入了箭头函数(Arrow Functions),提供更简洁的匿名函数语法:
php
<?php
$add = fn(int $a, int $b) => $a + $b;
echo $add(1, 2);
1.2 与匿名函数对比 #
php
<?php
$add = function(int $a, int $b): int {
return $a + $b;
};
$add = fn(int $a, int $b) => $a + $b;
1.3 单表达式 #
箭头函数只能包含一个表达式:
php
<?php
$square = fn($n) => $n ** 2;
$greet = fn($name) => "Hello, $name!";
$isEven = fn($n) => $n % 2 === 0;
二、语法详解 #
2.1 基本语法 #
php
<?php
fn(参数列表) => 表达式
2.2 无参数 #
php
<?php
$getTime = fn() => time();
$pi = fn() => M_PI;
echo $getTime();
echo $pi();
2.3 单参数 #
php
<?php
$double = fn($n) => $n * 2;
$upper = fn($s) => strtoupper($s);
echo $double(5);
echo $upper("hello");
2.4 多参数 #
php
<?php
$add = fn($a, $b) => $a + $b;
$format = fn($name, $age) => "$name is $age years old";
echo $add(1, 2);
echo $format("John", 25);
2.5 类型声明 #
php
<?php
$add = fn(int $a, int $b): int => $a + $b;
$greet = fn(string $name): string => "Hello, $name!";
echo $add(1, 2);
echo $greet("John");
2.6 可变参数 #
php
<?php
$sum = fn(...$numbers) => array_sum($numbers);
echo $sum(1, 2, 3, 4, 5);
三、自动变量捕获 #
3.1 自动捕获父作用域变量 #
箭头函数自动捕获父作用域的变量,无需使用use:
php
<?php
$message = "Hello";
$greet = fn($name) => "$message, $name!";
echo $greet("John");
3.2 与匿名函数对比 #
php
<?php
$factor = 10;
$multiply = function($n) use ($factor) {
return $n * $factor;
};
$multiply = fn($n) => $n * $factor;
3.3 值捕获 #
箭头函数捕获的是值,不是引用:
php
<?php
$counter = 0;
$increment = fn() => ++$counter;
echo $increment();
echo $counter;
3.4 多变量捕获 #
php
<?php
$prefix = "Hello";
$suffix = "!";
$greet = fn($name) => "$prefix, $name$suffix";
echo $greet("John");
四、在数组函数中使用 #
4.1 array_map #
php
<?php
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(fn($n) => $n ** 2, $numbers);
$doubled = array_map(fn($n) => $n * 2, $numbers);
print_r($squared);
print_r($doubled);
4.2 array_filter #
php
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
$greaterThan5 = array_filter($numbers, fn($n) => $n > 5);
print_r($even);
print_r($greaterThan5);
4.3 array_reduce #
php
<?php
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
$product = array_reduce($numbers, fn($carry, $n) => $carry * $n, 1);
echo $sum;
echo $product;
4.4 usort #
php
<?php
$users = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 20]
];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
print_r($users);
4.5 array_column结合 #
php
<?php
$users = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane']
];
$names = array_map(fn($u) => $u['name'], $users);
$ids = array_map(fn($u) => $u['id'], $users);
print_r($names);
print_r($ids);
五、对象方法调用 #
5.1 访问对象属性 #
php
<?php
class User
{
public function __construct(
public string $name,
public int $age
) {}
}
$user = new User("John", 25);
$getName = fn() => $user->name;
$getAge = fn() => $user->age;
echo $getName();
echo $getAge();
5.2 调用对象方法 #
php
<?php
class Calculator
{
public function add(int $a, int $b): int
{
return $a + $b;
}
}
$calc = new Calculator();
$add = fn($a, $b) => $calc->add($a, $b);
echo $add(1, 2);
六、嵌套箭头函数 #
6.1 返回箭头函数 #
php
<?php
function createMultiplier(int $factor): callable
{
return fn($n) => $n * $factor;
}
$double = createMultiplier(2);
$triple = createMultiplier(3);
echo $double(5);
echo $triple(5);
6.2 高阶函数 #
php
<?php
$compose = fn($f, $g) => fn($x) => $f($g($x));
$addOne = fn($x) => $x + 1;
$double = fn($x) => $x * 2;
$addOneThenDouble = $compose($double, $addOne);
echo $addOneThenDouble(5);
七、箭头函数的限制 #
7.1 单表达式限制 #
php
<?php
$valid = fn($n) => $n > 0 && $n < 100;
$invalid = fn($n) => {
$result = $n * 2;
return $result;
};
$valid = fn($n) => $n * 2;
7.2 不能修改捕获的变量 #
php
<?php
$counter = 0;
$increment = fn() => ++$counter;
$increment = function() use (&$counter) {
return ++$counter;
};
7.3 不能使用static #
php
<?php
$invalid = fn() => static $count = 0;
八、实际应用 #
8.1 数据转换 #
php
<?php
$products = [
['name' => 'Apple', 'price' => 100],
['name' => 'Banana', 'price' => 50],
['name' => 'Cherry', 'price' => 200]
];
$taxRate = 0.1;
$withTax = array_map(
fn($p) => [...$p, 'priceWithTax' => $p['price'] * (1 + $taxRate)],
$products
);
print_r($withTax);
8.2 条件过滤 #
php
<?php
$users = [
['name' => 'John', 'active' => true, 'role' => 'admin'],
['name' => 'Jane', 'active' => false, 'role' => 'user'],
['name' => 'Bob', 'active' => true, 'role' => 'user']
];
$activeAdmins = array_filter(
$users,
fn($u) => $u['active'] && $u['role'] === 'admin'
);
print_r($activeAdmins);
8.3 排序 #
php
<?php
$items = [
['name' => 'C', 'order' => 3],
['name' => 'A', 'order' => 1],
['name' => 'B', 'order' => 2]
];
usort($items, fn($a, $b) => $a['order'] <=> $b['order']);
print_r($items);
8.4 字符串处理 #
php
<?php
$strings = ['hello', 'world', 'php'];
$upper = array_map(fn($s) => strtoupper($s), $strings);
$lengths = array_map(fn($s) => strlen($s), $strings);
print_r($upper);
print_r($lengths);
九、箭头函数 vs 匿名函数 #
| 特性 | 箭头函数 | 匿名函数 |
|---|---|---|
| 语法 | 简洁 | 冗长 |
| 表达式 | 单个 | 多个 |
| 变量捕获 | 自动 | 需要use |
| 引用捕获 | 不支持 | 支持 |
| $this | 自动绑定 | 需要绑定 |
十、最佳实践 #
10.1 简单操作使用箭头函数 #
php
<?php
$squared = array_map(fn($n) => $n ** 2, $numbers);
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
10.2 复杂逻辑使用匿名函数 #
php
<?php
$processed = array_map(function($item) {
$result = complexCalculation($item);
logResult($result);
return $result;
}, $items);
10.3 需要引用时使用匿名函数 #
php
<?php
$counter = 0;
$increment = function() use (&$counter) {
return ++$counter;
};
十一、总结 #
本章学习了:
- 箭头函数语法
- 自动变量捕获
- 在数组函数中的应用
- 箭头函数的限制
- 与匿名函数的对比
- 最佳实践
下一章将学习类型声明。
最后更新:2026-03-26