Attributes เป็นชนิดหนึ่งของคลาสที่สามารถใช้เพื่อเพิ่ม metadata ให้กับคลาส ฟังก์ชัน เมธอดของคลาส พรอเพอร์ตี้ของคลาส ค่าคงที่ และพารามิเตอร์ Attributes ไม่ทำอะไรในระหว่าง runtime
Attributes ไม่มีผลกระทบต่อโค้ด แต่พร้อมใช้งานสำหรับ Reflection API Attributes ใน PHP 8 อนุญาตให้โค้ดอื่นตรวจสอบพรอเพอร์ตี้และเมธอดของคลาสได้
เราสามารถมี attribute มากกว่าหนึ่งสำหรับการประกาศเดียว
อาจ resolve ชื่อคลาสได้
Attributes สามารถเป็น namespaced ได้
อาจมีพารามิเตอร์ศูนย์หรือมากกว่า
รูปแบบ Attribute ใน PHP 8
ใน PHP 8 #[ ] (# และวงเล็บเหลี่ยม) ใช้สำหรับการประกาศ attribute
เราสามารถประกาศ multiple attributes ภายใน #[ ] คั่นด้วยคอมม่า
อาร์กิวเมนต์เป็น optional แต่ต้องอยู่ในวงเล็บ ()
อาร์กิวเมนต์สามารถเป็นค่าคงที่หรือนิพจน์คงที่ได้
Attribute: Syntax
#[attribute]
เราสามารถใช้ attribute กับคลาสได้ตัวอย่าง
#[Attribute] Final class EmpClass{ }
ตัวอย่าง: Attribute Function
#[Attr('param')] function Exam(){}
ตัวอย่าง: Attribute Classes
#[Attr('param')] class Exam{}
ตัวอย่าง: Attribute Class Properties
class Emp{ #[Attribute('param')] public $name; }
ตัวอย่าง: Attribute Class Constants
Class Emp{ #[Attribute('emp')] private const EMP = 'emp'; }
ตัวอย่าง: Attribute Function
#[Attribute('emp')] function exam(){}
ตัวอย่าง: Attribute Method Arguments
Function emp(#[Attribute('param')]$name){ }
ตัวอย่าง: PHP 8 Attribute ใช้กับฟังก์ชัน เมธอด พารามิเตอร์ และค่าคงที่
<?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);
?>
ผลลัพธ์
Closure Object ( )