大网数据广告活动
PHP 语言与运行手册

The DelayedTargetValidation attribute

· 52CE 我爱测

This attribute delays target validation errors for internal attributes from compile time to when the attribute is instantiated via the Reflection API.

The DelayedTargetValidation attribute

(PHP 8 >= 8.5.0)

Introduction

This attribute delays target validation errors for internal attributes from compile time to when the attribute is instantiated via the Reflection API.

When applied to a declaration, any invalid usage of internal attributes on the same target will not trigger a compile time error. Instead, the validation is deferred and performed when the attribute is instantiated via ReflectionAttribute::newInstance().

This is primarily intended for forward compatibility, allowing code to use attributes that may gain additional valid targets in future PHP versions without breaking on older versions.

Class synopsis

#[\Attribute(\Attribute::TARGET_ALL)]
final class DelayedTargetValidation {
}

Examples

Example #1 Delaying validation of an invalid target

<?php

class Base {
    public const NAME = 'base';

    protected function foo(): void {}
}

class Child extends Base {

    #[\DelayedTargetValidation]
    #[\Override]
    public const NAME = 'child';

    #[\Override]
    protected function foo(): void {}
}

On PHP versions where Override is not allowed on class constants, this does not produce a compile time error. As of PHP 8.6.0, Override can target class constants, and Child::NAME overrides Base::NAME, DelayedTargetValidation is then no longer needed here, and the reflection example below no longer throws for it.

Example #2 Validation occurs during reflection

<?php

$reflection = new ReflectionClassConstant(Child::class, 'NAME');

foreach ($reflection->getAttributes() as $attribute) {
    $attribute->newInstance(); // May throw if invalid
}

When any attribute applied to the same target (other than DelayedTargetValidation itself) is instantiated via reflection using ReflectionAttribute::newInstance(), target validation is performed and an exception may be thrown if the attribute is used on an unsupported target.

Notes

This attribute only affects target validation of internal attributes.

It does not suppress functional validation performed by those attributes. For example, Override will still emit an error if a method does not actually override a parent method.

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。