

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ( )
- Related Questions & Answers
- Reading Attributes with Reflection API in PHP 8
- Named Arguments in PHP 8
- Union Type in PHP 8
- Number comparisons in PHP 8
- Match Expression in PHP 8
- Nullsafe Operator in PHP 8
- fdiv() function in PHP 8
- Mixed Pseudo Type in PHP 8
- Constructor Property Promotion in PHP 8
- Difference between gettype() in PHP and get_debug_type() in PHP 8
- $object::class in PHP 8 and get_class($object) in PHP
- What is Stringable Interface in PHP 8?
- str_starts_with and str_ends_with function in PHP 8
- Convert ASCII TO UTF-8 Encoding in PHP?
- How to get resource ID using get_resource_id() function in PHP and PHP 8?