Attributes là các lớp dùng để thêm metadata cho lớp khác, hàm, phương thức lớp, thuộc tính lớp, hằng số, và tham số. Attributes không làm gì tại runtime.
Attributes không ảnh hưởng code, nhưng có sẵn cho Reflection API. Attributes trong PHP 8 cho phép code khác kiểm tra thuộc tính và phương thức lớp.
Có thể có nhiều hơn một attribute cho một khai báo.
Có thể giải quyết tên lớp.
Attributes có thể có namespace.
Có thể có zero hoặc nhiều tham số.
Cú pháp Attribute PHP 8
Trong PHP 8, #[ ] (# và ngoặc vuông) dùng cho khai báo attribute.
Có thể khai báo nhiều attribute trong #[ ], phân cách bằng dấu phẩy.
Tham số tùy chọn nhưng cần trong ngoặc đơn ().
Tham số có thể là giá trị literal hoặc biểu thức hằng.
Attribute: Cú pháp
#[attribute]
Có thể dùng attribute cho lớp.
#[Attribute] Final class EmpClass{ }
Ví dụ: Attribute Function
#[Attr('param')] function Exam(){}
Ví dụ: Attribute Classes
#[Attr('param')] class Exam{}
Ví dụ: Attribute Class Properties
class Emp{ #[Attribute('param')] public $name; }
Ví dụ: Attribute Class Constants
Class Emp{ #[Attribute('emp')] private const EMP = 'emp'; }
Ví dụ: Attribute Function
#[Attribute('emp')] function exam(){}
Ví dụ: Attribute Method Arguments
Function emp(#[Attribute('param')]$name){ }
Ví dụ: PHP 8 Attribute dùng cho functions, methods, parameters, 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);
?>
Kết quả
Closure Object ( )