Everything about PHP 8 Attributes

Tags:

Annotation officially coming to PHP. Its available from version PHP 8. This is similar to annotation in another language. Till now PHP did not supported annotation but we were using it with the help of documentation annotation.

In this blog we will explain everything about annotation and how it will impact nishchay framework. As nishchay is using documentation annotation which will be changed to PHP attribute in future release of nishchay framework.

To avoid confusion PHP 8 named it attribute. So Annotation is meta data which are defined in doc comment while PHP 8 attributes are native.

What is Attribute

Attribute will be as to provide meta data information for class, method, property. To understand this let's take an example of how routes are defined in nishchay framework.

To define route we @Route annotation. see below code.

/**
* @Route(path='blog')
*/
public function blog(){
}

This defines route with path blog. Once nishchay framework will start supporting attribute above can be changed to

#[Route('blog')]
public function blog(){
}

NOTE Attributes in PHP 8 are defined within << and >> brackets.

Using attribute

Attributes are class in PHP so if you want to use it you can import the way you do with PHP classes. Suppose we have attribute Nishchay\Route\Route and we want to apply to any of method. We can import it using use statement then we can use it directly.


use Nishchay\Route\Route; class BlogController { #[Route('path')] public function blog(){ } }

This is similar to creating instance of class but without new keyword or say calling function.

Where to define attribute

We can define attribute before method name or before doc comment.

Example

Attributes can be applied to all of the following 1. Function 2. Class 3. Class method 4. Class property 5. Class constant 6. Method arguments 7. Closure 8. Anonymous class.

Let's go through each of above list to understand how attribute can be applied to all of them.

Function
#[Attribute('param')]
function fn(){
}
Class
#[Attribute('param')]
Class Test{
}
Class method
class Test {
    #[Attribute('param')]
    public function fn(){
    }
}
Class property
class Test {

    #[Attribute('param')]
    public $name;
}
Class constant
class Test {

    #[Attribute('param')]
     const NAME;
}
Method arguments
function test(#[Attribute('param')] $name) {
}
Closure
$callback = #[Attribute('param')] function () {
}
Anonymous class
$instnace = #[Attribute('param')] new class {}
Custom Attribute

To create custom attribute, create class and then define #[Attribute] on class. Then this class can be used as attribute.


#[Attribute] class CusotmAttribute { }