Attributes in PHP 8



Attributes are kinds of classes that can be used to add metadata to other classes, functions, class methods, class properties, constants, and parameters. Attributes do nothing during runtime.

Attributes have no impact on the code, but available for the reflection API. Attributes in PHP 8 allow other code to examine the class properties and methods.

  • We can have more than one attribute to a declaration.

  • It may resolve the class name.

  • Attributes can be namespaced.

  • It may have zero or more parameters

PHP 8 Attribute Syntax

  • In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration.

  • We can declare multiple attributes inside #[ ], separated by a comma.

  • Arguments are optional to use but need to be enclosed inside parenthesis ().

  • Arguments can be literals values or constant expressions.

Attribute: Syntax

#[attribute]

We can use an attribute to a class for instance.

#[Attribute]
Final class EmpClass{
}

Example: Attribute Function

#[Attr('param')]
function Exam(){}

Example: Attribute Classes

#[Attr('param')]
class Exam{}

Example: Attribute Class Properties

class Emp{
   #[Attribute('param')]
   public $name;
}

Example: Attribute Class Constants

Class Emp{
   #[Attribute('emp')]
   private const EMP = 'emp';
}

Example: Attribute Function

#[Attribute('emp')]
function exam(){}

Example: Attribute Method Arguments

Function emp(#[Attribute('param')]$name){
}

Example: PHP 8 Attribute using functions, methods, parameters and constants

<?php
#[MyAttribute]
class Emp
{
   #[MyAttribute]
   public const EMP = 'emp';
   #[MyAttribute]
   public $a;
   #[MyAttribute]
   public function foo(#[MyAttribute] $dept){}
}

$object = new #[MyAttribute] class(){};
#[MyAttribute]
function f() {}

$f1 = #[MyAttribute] function(){};
$f2 = #[MyAttribute] fn() => 1;
print_r($f1);
?>

Output

Closure Object ( )
Updated on: 2021-04-01T06:24:08+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements