What defines an attribute class in PHP 8?

Asked

Viewed 111 times

-2

I am using PHP 8 attributes, the documentation of this feature is still rudimentary, it only contains code examples and the api is not documented so I am experiencing the use of the resource.

class MeuAtributo {}

#[MeuAtributo]
class Teste {}

$reflection = new ReflectionClass(Teste::class);
$attributes = $reflection->getAttributes();
var_dump($attributes[0]->newInstance());

When executing this code the following error occurs in the call of newInstance():

Attempting to use non-attribute class "MeuAtributo" as attribute in /code/index.php:10
  • What is the attribute class mentioned in the message?
  • How to correct this error?
  • 3

    Usually, I usually close like typo questions that have something like "forgot to put X" by inattention or have missed a detail unnoticed from documentation, or even "syntax error". Here at stackoverflow it is interesting that the questions are formulated in a way that helps not only oneself, but also other users. As far as I was concerned, there was a lack of attention when it came to implementing Attribute.

  • 1

    I forgot that time to leave the documentation link to help a little. It’s still in English, only.

  • Is this Reflection feature new to PHP or have you always had it? If it’s not Java, it’s unnecessary in 99% of cases, and I wouldn’t advise learning much, just knowing it exists. Most of the cases you think you can use will be better done without. And if it is not even Java is slow. Just Saying

  • @Piovezan Reflection PHP has been available since 2004 with version 5. I have no performance information. but I know that some frameworks use (in dependency injection). Specifically for the attribute part/reflection Annotations is the only way to access this resource (in C# as well)

  • @Pedrosanction Necessary it is, otherwise it would not have been created, but in final application code tends to be misused. It’s the kind of resource to keep in mind along with multiple inheritance, operator overload and stuff like that. But in this case of attributes I can be talking nonsense because I don’t know what this attribute feature is like in PHP, it must be different from fields as in the conceptual, but I looked over the code and interpreted as picking fields of the object (P.S.: Now I get it, they’re like the Java Annotations themselves. Well, they keep being turned over to p/create frameworks, no?).

  • @Pedrosanção Cara, I’m sorry, I got into the question and I started talking about everything on a hypothetical level and I didn’t even realize that you are using attributes/Reflection, I thought you were just trying to understand how they work. I did not intend to criticize this specific use, which I don’t even know what it is. I didn’t get into the merit, I just generalized.

  • All right @Piovezan. I think Annotation is the equivalent in Java yes

  • Well, if it’s like in Java, the trend is the same one that I talked about for custom Reflection and Annotations, knowing that they exist, being aware of how they work, and leaving more for frameworks to use: https://dzone.com/articles/creating-custom-annotations-in-java and https://stackoverflow.com/q/9222621/2241463 In dynamic languages like PHP Reflection can have the added advantage of converting strings into fields of an object or the opposite, and perhaps also methods, which may be a little more useful in some cases.

Show 4 more comments

1 answer

0


TD; DR:

To define an add class attribute class #[Attribute] before class:

namespace App;

use Attribute;

#[Attribute]
class MeuAtributo {}

The use is necessary only when the class uses namespace, as in this example.


Understanding class of attributes

The definition of attribute classes is described on this page of the manual (no translation). Still I find it useful to make a parallel with languages that already use this resource, such as C# for example, because it lacks conceptual description of the resource.

Attributes provide an efficient method of associating metadata, or declarative information, to code (classes, methods and properties, functions, class constants, parameters). After an attribute is associated with a program entity, the attribute can be consulted at runtime using a technique called reflection.

Attributes have the following properties:

  • Attributes add metadata to your program. Metadata is information about the types defined in a program. You can add custom attributes to specify any additional information required.
  • You can apply one or more attributes to classes, methods and properties, etc.
  • Attributes can accept arguments.
  • Your program can examine its own metadata or metadata in other programs using reflection.

An attribute class is a class that derives directly or indirectly from the class Attribute, which makes the identification of attribute definitions in the metadata quick and easy. Suppose you want to mark types with the name of the programmer who wrote the type. You can define a class of attributes Author customized.

In practice

Attribute has an optional parameter to limit where this attribute class can be used, this argument accepts a combination of constants using | (bit operator "OR"):

Attribute::TARGET_ALL;
Attribute::TARGET_CLASS;
Attribute::TARGET_CLASS_CONSTANT;
Attribute::TARGET_FUNCTION;
Attribute::TARGET_METHOD;
Attribute::TARGET_PARAMETER;
Attribute::TARGET_PROPERTY;

For example:

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class Exemplo {}

Will allow the attribute class Exemplo is used only as method and function attributes.

About the mistakes

The error highlighted is actually an exception and can be captured with try/catch. It occurs when there is a problem with the implementation, whether it is the missing attribute (the error pointed out in the question) or a use restriction (described above).

  • I think we missed the use Attribute;, if I’m not mistaken, needs it

  • @Costamilam would only need the use if the file used namespace, as in this example was not used it is not necessary

  • If you want, you can add this to the answer, to make it more complete

Browser other questions tagged

You are not signed in. Login or sign up in order to post.