PHP 8.6.0RC7 available for testing

ReflectionAttribute::newInstance

(PHP 8)

ReflectionAttribute::newInstance — Instantiates the attribute class represented by this ReflectionAttribute class and arguments

Опис

public function ReflectionAttribute::newInstance(): object

Instantiates the attribute class represented by this ReflectionAttribute class and arguments.

Параметри

У цієї функції немає параметрів.

Значення, що повертаються

New instance of the attribute.

Помилки/виключення

Throws an Error if the attribute class cannot be loaded, or if the class is not declared with #[Attribute].

Throws an Error if the attribute is applied to a target it cannot be used on, or if it is applied more than once and is not declared with Attribute::IS_REPEATABLE. For internal attributes, target validation happens here instead of at compile time when the declaration uses #[\DelayedTargetValidation].

Errors and exceptions thrown by the attribute constructor are propagated.

Журнал змін

Версія Опис
8.5.0 Now throws an Error for an internal attribute applied to an invalid target when the target validation was delayed with #[\DelayedTargetValidation].
+add a note

User Contributed Notes 1 note

up
-1
baptiste at pillot dot fr
3 years ago
Calling ReflectionAttribute::newInstance() using an attribute name that does not have a corresponding class will result in an error.

Example :

<?php
#[FakeAttribute]
class Test {}

try {
  (new ReflectionClass(Test::class))->getAttributes()[0]->newInstance();
}
catch (Error $error) {
  echo 'Throwed error ' . get_class($error) . ' with message : ' . $error->getMessage();
}
?>

This will output :

Throwed error Error with message : Attribute class "FakeAttribute" not found
To Top