



























PHP 8.5 于 2025 年 11 月 20 日发布,本次更新引入了管道操作符(Pipe Operator)、clone with 功能、全新的 URI 解析器等实用特性。下面我们来详细看看这些新功能。
PHP 8.5 新增了管道操作符,使函数链式调用更加简洁。
传统写法可能是这样:
$input = ' Some kind of string. ';
$output = strtolower(
str_replace(['.', '/', '…'], '',
str_replace(' ', '-',
trim($input)
)
)
);
使用管道操作符后,可以这样写:
$output = $input
|> trim(...)
|> (fn (string $string) => str_replace(' ', '-', $string))
|> (fn (string $string) => str_replace(['.', '/', '…'], '', $string))
|> strtolower(...);
这种写法可读性更高,逻辑更直观。
现在可以在克隆对象的同时赋新值:
final class Book
{
public function __construct(
public string $title,
public string $description,
) {}
public function withTitle(string $title): self
{
return clone($this, [
'title' => $title,
]);
}
}
注意,readonly 属性在外部仍然不能直接克隆修改,需要显式设置为可写。
可以通过 #[NoDiscard] 标记函数返回值必须被使用,否则会触发警告:
#[NoDiscard("你必须使用这个返回值")]
function foo(): string {
return 'hi';
}
// 警告:
foo();
// 正确:
$string = foo();
如果确实要忽略返回值,可以使用 (void):
(void) foo();
闭包和一等可调用函数现在可以用于常量表达式,支持在属性中定义闭包:
#[SkipDiscovery(static function (Container $container): bool {
return ! $container->get(Application::class) instanceof ConsoleApplication;
})]
final class BlogPostEventHandlers
{ /* … */ }
注意闭包必须显式标记 static,且不能访问外部变量。
PHP 8.5 的致命错误现在会输出完整的回溯(backtrace),便于调试:
Fatal error: Maximum execution time of 1 second exceeded in example.php on line 6
Stack trace:
#0 example.php(6): usleep(100000)
#1 example.php(7): recurse()
...
相比以前使用 array_key_first 和 array_key_last 更简洁。
PHP 8.5 引入了全新的 URI 解析器,使 URI 处理更加方便:
use Uri\Rfc3986\Uri;
$uri = new Uri('https://tempestphp.com/2.x/getting-started/introduction');
$uri->getHost();
$uri->getScheme();
$uri->getPort();
某些内置属性默认在编译时验证,使用 #[DelayedTargetValidation] 可以将验证延迟到运行时,有助于兼容旧代码:
class Child extends Base
{
#[DelayedTargetValidation]
#[Override]
public const NAME = 'Child';
}
完整列表可参考官方 GitHub 页面。
PHP 8.5 带来了很多让开发者更高效的特性,无论是函数链式调用、对象克隆赋值,还是闭包增强,都提升了代码可读性和可维护性。你最期待哪一个新特性呢?

Don’t reinvent the wheel, library code is there to help.
欢迎关注公-众-号【TaonyDaily】、留言、评论,一起学习。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。