PHP 8.6 是 PHP 语言的一次重大更新,新增了 Partial Function Application、Duration 类、Polling API 和 clamp() 函数等功能。
更具表达力的代码、更严格的类型、可扩展的 I/O。
允许预先提供函数的部分参数,并返回一个接收其余参数的 Closure。
\Time\Duration 类
Duration 类用于表示像秒表一样测量的经过时间。
通过 epoll、kqueue 等原生机制提供可扩展的 I/O 多路复用,可供 ReactPHP、AMPHP 等事件循环库使用。
clamp() 函数
确保给定值处于指定范围内,既适用于数值,也适用于其他类型的值。
SortDirection 枚举
提供标准且类型安全的排序方向表示方式,可供不同的库共同使用。
允许为 readonly 属性声明默认值,无需再在构造函数中为其赋予固定值。
允许预先提供函数的部分参数,并用 ? 和 ... 为其余参数占位。返回结果是一个 Closure,只有在向其传入剩余参数后,才会调用原函数。
$versions = ['8.4', '8.5', '8.6', '8.7', '9.0'];
$supportsPfa = array_filter(
$versions,
fn ($version) => version_compare($version, '8.6', '>='),
);\Time\Duration 类Duration 类用于表示像秒表一样测量的经过时间。它不依赖具体时刻或时区,能够以纳秒精度表示超过 250 年的时间跨度,非常适合清晰地表达超时时长或基准测试耗时。
/**
* All delays are in microseconds.
*/
function backoff(
int $baseDelay,
int $step,
int $attempt,
): void {
$delay = $baseDelay + ($step * (2 ** $attempt));
// Wait at most 30 seconds.
usleep(min($delay, 30_000_000));
}
// 1 second base delay, plus 100 milliseconds
// doubling with each attempt.
backoff(1_000_000, 100_000, $attempt);use Time\Duration;
function backoff(
Duration $baseDelay,
Duration $step,
int $attempt,
): void {
$delay = $baseDelay->add($step->multiplyBy(2 ** $attempt));
// Durations are comparable, so min() works directly.
$delay = min($delay, Duration::fromSeconds(30));
time_nanosleep($delay->seconds, $delay->nanoseconds);
}
backoff(
Duration::fromSeconds(1),
Duration::fromMilliseconds(100),
$attempt,
);
// Preconfigure the delays using Partial Function Application.
$waitBeforeRetry = backoff(
Duration::fromSeconds(1),
Duration::fromMilliseconds(100),
attempt: ?,
);
$waitBeforeRetry($attempt);全新的 Io\Poll API 使用各平台上最合适的机制(epoll、kqueue、event ports 或 WSAPoll)高效地同时监控大量流,突破了 stream_select() 的可扩展性限制。它旨在为 ReactPHP、AMPHP 等事件循环库提供通用基础。
$server = stream_socket_server('tcp://0.0.0.0:8080');
$clients = [];
while (true) {
$read = [$server, ...$clients];
$write = $except = null;
// Based on select(), which typically can't handle
// more than 1024 connections
stream_select($read, $write, $except, null);
foreach ($read as $stream) {
if ($stream === $server) {
$clients[] = stream_socket_accept($server);
continue;
}
$data = fread($stream, 8192);
if ($data === '' || $data === false) {
$key = array_search($stream, $clients, true);
unset($clients[$key]);
fclose($stream);
} else {
fwrite($stream, $data);
}
}
}use Io\Poll\{Context, Event};
$server = stream_socket_server('tcp://0.0.0.0:8080');
// Automatically uses epoll, kqueue, event ports, or WSAPoll
$poll = new Context();
$poll->add(new StreamPollHandle($server), [Event::Read]);
while (true) {
foreach ($poll->wait() as $watcher) {
$stream = $watcher->getHandle()->getStream();
if ($stream === $server) {
$client = stream_socket_accept($server);
$poll->add(
new StreamPollHandle($client),
[Event::Read],
);
continue;
}
$data = fread($stream, 8192);
if ($data === '' || $data === false) {
$watcher->remove();
fclose($stream);
} else {
fwrite($stream, $data);
}
}
}现在可以将流操作配置为在出错时抛出 StreamException,或静默失败,而不再发出警告。错误以结构化的 StreamError 对象形式报告,其中包含 StreamErrorCode 枚举项、封装器名称以及受影响的路径或 URL。还可以稍后通过 stream_last_errors() 获取这些错误,或将其传递给自定义错误处理函数。
$config = @file_get_contents('/etc/app/config.json');
if ($config === false) {
// Only an unstructured message string is available
$error = error_get_last();
log_error($error['message']);
}$context = stream_context_create([
'stream' => [
'error_mode' => StreamErrorMode::Exception,
],
]);
try {
$config = file_get_contents(
'/etc/app/config.json',
context: $context,
);
} catch (StreamException $e) {
foreach ($e->getErrors() as $error) {
// $error->code is a StreamErrorCode enum case
log_error(
$error->code->name,
$error->message,
$error->wrapperName,
);
}
}clamp() 函数确保给定值处于指定范围内,既适用于数值,也适用于其他类型的值。如果超出范围,则返回最接近的边界值。
var_dump(max(0, min(-10, 100)));
// int(0)
var_dump(max(0, min(50, 100)));
// int(50)
var_dump(max(0, min(110, 100)));
// int(100)var_dump(clamp(-10, 0, 100));
// int(0)
var_dump(clamp(50, 0, 100));
// int(50)
var_dump(clamp(110, 0, 100));
// int(100)
// Any comparable value works with clamp(). This
// includes the new Duration class.
var_dump(clamp(
\Time\Duration::fromSeconds(30),
min: \Time\Duration::fromMinutes(1),
max: \Time\Duration::fromMinutes(10),
)->seconds);
// int(60)SortDirection 枚举SortDirection 枚举通过 Ascending 和 Descending 两个枚举项,提供通用且类型安全的排序方向表示方式。此前,各个库必须自行定义排序方向,导致整数、字符串、布尔值和自定义枚举等互不兼容的表示方式混杂使用。由于 SortDirection 内置于 PHP,库可以直接在公共 API 中接收它,无需编写适配代码。
可在 The PHP Foundation 的博客中进一步了解此特性。
class QueryBuilder
{
private array $orderBy = [];
public function orderBy(
string $column,
int $direction = SORT_ASC,
): static {
$this->orderBy[] = $column . ' ' . match ($direction) {
SORT_ASC => 'ASC',
SORT_DESC => 'DESC',
};
return $this;
}
}
$qb->orderBy('name', SORT_DESC);
$qb->orderBy('name', SORT_STRING);
// Accepted by the signature, then fails inside the method:
// UnhandledMatchError: Unhandled match case 2class QueryBuilder
{
private array $orderBy = [];
public function orderBy(
string $column,
SortDirection $direction = SortDirection::Ascending,
): static {
$this->orderBy[] = $column . ' ' . match ($direction) {
SortDirection::Ascending => 'ASC',
SortDirection::Descending => 'DESC',
};
return $this;
}
}
$qb->orderBy('name', SortDirection::Descending);
$qb->orderBy('name', SORT_STRING);
// TypeError: QueryBuilder::orderBy(): Argument #2 ($direction)
// must be of type SortDirection, int given函数和方法的参数现在可以拥有各自的 DocComments,并可通过新增的 ReflectionParameter::getDocComment() 方法获取。这样就能直接在每个参数的声明旁编写文档,无需在 @param 标签中重复参数名称和类型。
class DB
{
/**
* Returns up to $limit items matching the $query.
*
* @param string $query Terms to search
* @param int $limit Maximum number of results
*/
public function search(string $query, int $limit = 10): array
{
return [];
}
}
// Parameter descriptions can only be extracted
// by parsing the function's DocComment.class DB
{
/**
* Returns up to $limit items matching the $query.
*/
public function search(
/** Terms to search */
string $query,
/** Maximum number of results */
int $limit = 10,
): array {
return [];
}
}
var_dump(
new ReflectionParameter([DB::class, 'search'], 'query')
->getDocComment(),
);
// string(22) "/** Terms to search */"ReflectionProperty::isReadable() 和 ReflectionProperty::isWritable() 方法随着 readonly 属性、不对称可见性和属性钩子的引入,仅检查属性是否为 public 已不足以判断它能否被读取或写入。这两个新方法可以直接判断属性在给定作用域下是否可读或可写,也可以针对特定对象进行判断,并综合考虑可见性、初始化状态、钩子和魔术方法。
class NewsEntry
{
public string $title = 'PHP 8.6 released!';
public private(set) string $slug = 'php-86-released';
}
$entry = new NewsEntry();
foreach (['title', 'slug'] as $item) {
$property = new ReflectionProperty(NewsEntry::class, $item);
printf(
"%s: isReadable=%s isWritable=%s\n",
$item,
$property->isReadable(null, $entry) ? 'yes' : 'no',
$property->isWritable(null, $entry) ? 'yes' : 'no',
);
}
// title: isReadable=yes isWritable=yes
// slug: isReadable=yes isWritable=no现在可以为实例的 readonly 属性声明默认值,包括 readonly 类中的属性。这让实现具有固定值的仅可读接口属性变得更简单,而此前必须在构造函数中为这些属性赋值。声明默认值即完成了属性初始化,因此构造函数无法再覆盖该值。
interface Rule
{
public string $parser { get; }
}
final readonly class SlugRule implements Rule
{
public string $parser;
public function __construct()
{
$this->parser = SlugParser::class;
}
}#[\Override] 注解现在可以用于类常量和枚举项。__debugInfo() 魔术方法。Config::DEFAULTS->timeout = 30。Uri\Rfc3986\UriBuilder 和 Uri\WhatWg\UrlBuilder 类,可根据各组成部分构建 URI,同时新增了用于检测 URI 类型和主机类型的方法,以及 Uri\WhatWg\url_percent_encode() 函数。mysqli::quote_string() 方法,用于转义字符串并为其加上引号,行为与 PDO::quote() 一致。pack() 和 unpack() 现在支持在整数和浮点数格式码上使用 < 和 > 字节序修饰符。error_include_args INI 设置,用于统一控制在错误消息中包含函数参数。grapheme_strrev() 函数,可按字素簇反转字符串;新增 IntlNumberRangeFormatter 类,用于格式化数值范围。ZipArchive::openString() 和 ZipArchive::closeString() 方法,用于处理内存中的归档文件。array_map() 调用编译为循环、加快 printf() 调用、缓存无状态闭包,以及加快 JSON 编码。finally 块中使用 return 现已弃用,因为它会静默丢弃异常,并覆盖 try 或 catch 块的返回值。__construct() 或 __destruct() 返回值的行为现已弃用,将它们用作生成器的行为也已弃用。为 __debugInfo() 声明可空返回类型也已弃用。let 或 is 用作类名、函数名或常量名现已弃用。将 _ 用作常量名、将 namespace 用作类常量名,以及将 readonly 用作函数名也已弃用。mb_ereg() 和 mb_split() 等 mbstring 正则表达式函数现已弃用。可改用带 u 修饰符的 PCRE 函数。is_double()、is_long()、is_integer() 和 doubleval() 这些别名现已弃用。请改用 is_float()、is_int() 和 floatval()。spl_object_hash() 现已弃用,请改用 spl_object_id();spl_classes() 也已弃用,请改用 ReflectionExtension::getClassNames()。array_walk()、array_walk_recursive()、http_build_query()、mb_convert_variables() 以及压缩函数和过滤器中应接收数组的位置传入对象,现已弃用。请先使用 get_object_vars() 将对象转换为数组。strcoll() 和 SORT_LOCALE_STRING 排序标志现已弃用。请改用 intl 扩展的 Collator 类。define() 传入第三个参数现已弃用。在 $allow_string 为 false 时,使用类名字符串调用 is_a() 或 is_subclass_of() 也已弃用。filter.max_filter_count 上下文选项的情况下,在 php://filter URL 中使用超过 16 个过滤器的行为现已弃用。session.use_strict_mode 和 session.cookie_httponly,并将 session.cookie_samesite 设为 Lax。create_sid() 和 validateId() 的自定义会话处理器现已弃用。metaphone()、mysqli_get_charset() 和 mysqli_stmt_init() 函数现已弃用。此外,SplFileObject 的 CSV 方法,以及 ArrayIterator 的排序、标志和序列化方法也已弃用。trim()、ltrim() 和 rtrim() 现在默认也会移除换页符(\f)。fclose()、file_put_contents() 和 copy() 现在会返回 false,而不再静默忽略失败。ValueError,而不再静默截断或忽略它们。