编程

PHP 8.5: #[\Deprecated] 可用于 trait

6 2025-12-10 14:14:00

#[\Deprecated] 注解是 PHP 8.4 中引入的,可用于调用函数(或类方法)或者访问类常量(或者枚举 case)时发出弃用警告。从 8.5 开始,弃用警告也可以用在访问全局常量时发出。而本文将介绍该注解在 PHP 8.5 中引入的另一个新特性:支持 trait 的弃用警告。

<?php
 
#[\Deprecated]
trait DemoTrait {}
 
class DemoClass {
	use DemoTrait;
}
 
// Reports:
// Deprecated: Trait DemoTrait used by DemoClass is deprecated in %s on line %d
?>

#[\Deprecated] 注解允许用于 trait。由于 Attribute::TARGET_CLASS 包含 trait 以及类、接口和枚举,因此会使用验证器来确保当应用于“类”(zend_class_entry)时,它必须对应于一个 trait。

当加载类使用的 trait 时,任何已弃用的 trait 都会发出弃用警告信息;这些信息可以通过用户错误处理程序转换为异常,而未捕获的异常在注册行为方面将被视为尝试将非 trait 对象用作 trait。

Trait 仅在直接使用时才会发出弃用警告,使用已弃用 trait 的类的子类不会发出任何额外的错误,除非它们也直接使用了该 trait。

示例

简单示例:

<?php
 
#[\Deprecated]
trait DemoTrait {}
 
class DemoClass {
	use DemoTrait;
}
 
// Reports:
// Deprecated: Trait DemoTrait used by DemoClass is deprecated in %s on line %d
?>

使用异常:

<?php
 
function my_error_handler(int $errno, string $errstr, ?string $errfile = null, ?int $errline = null) {
	throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
}
 
set_error_handler('my_error_handler');
 
#[\Deprecated]
trait DemoTrait {}
 
class DemoClass {
	use DemoTrait;
}
 
// Reports:
// Fatal error: Uncaught ErrorException: Trait DemoTrait used by DemoClass is deprecated in %s:%d
 
?>