Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Attributes in PHP 8
Attributes in PHP 8 are special classes that add metadata to other classes, functions, methods, properties, constants, and parameters. They provide a structured way to add meta−information without affecting runtime behavior.
Attributes have no impact on code execution but are accessible through PHP's reflection API. This allows other code to examine and process the metadata attached to various code elements.
Key Features
Multiple attributes can be applied to a single declaration
Attribute class names are resolved like regular classes
Attributes can be namespaced for better organization
Parameters are optional but must use parentheses when present
Syntax
PHP 8 uses #[ ] (hash symbol with square brackets) for attribute declarations ?
#[AttributeName]
#[AttributeName('parameter')]
#[Attr1, Attr2('param1', 'param2')]
Examples
Basic Attribute Usage
Here's a comprehensive example showing attributes applied to various code elements ?
<?php
#[MyAttribute]
class Emp
{
#[MyAttribute]
public const EMP_TYPE = 'permanent';
#[MyAttribute('name_field')]
public $name;
#[MyAttribute]
public function getInfo(#[MyAttribute] $department)
{
return "Employee in $department";
}
}
// Attribute on anonymous class
$object = new #[MyAttribute] class() {};
// Attribute on function
#[MyAttribute]
function processEmployee() {
return "Processing employee";
}
// Attribute on closures
$closure1 = #[MyAttribute] function() { return "Closure 1"; };
$closure2 = #[MyAttribute] fn() => "Arrow function";
echo processEmployee();
?>
Processing employee
Using Reflection to Access Attributes
Attributes become useful when accessed through reflection ?
<?php
#[Deprecated('Use NewClass instead')]
class OldClass
{
#[Required]
public $name;
}
$reflection = new ReflectionClass('OldClass');
$attributes = $reflection->getAttributes();
foreach ($attributes as $attribute) {
echo "Attribute: " . $attribute->getName() . "
";
print_r($attribute->getArguments());
}
?>
Attribute: Deprecated
Array
(
[0] => Use NewClass instead
)
Conclusion
PHP 8 attributes provide a clean, native way to add metadata to code elements. They're particularly useful for frameworks, documentation tools, and code analysis where structured metadata is needed without affecting runtime performance.
