#! 需要 PHP >= 8.0
#! 這是範例
<?php
declare(strict_types = 1);
#[Attribute]
class Foo
{
function __construct(){
echo "執行中 " . __METHOD__ . PHP_EOL;
}
}
#[Attribute(Attribute::TARGET_CLASS|Attribute::IS_REPEATABLE)]
class Bar {
function __construct(?string ...$args){
echo "執行中 " . __METHOD__ ,
" 參數: " . implode(", ", $args) . PHP_EOL;
}
}
#[Attribute(Attribute::TARGET_ALL)]
class Baz {
function __construct(
private string $parameter
){
echo "執行中 " . __METHOD__ ,
" 參數: " . $this->parameter . PHP_EOL;
}
}
#[Foo] #[Bar] #[Bar("香蕉")] #[Bar("香蕉", "蘋果", "檸檬", "葡萄")] #[Baz("唯一的一個")] class Qux
{
}
$ref = new ReflectionClass(Qux::class);
$attrs = $ref->getAttributes(); $attrs[0]->newInstance(); $attrs[1]->newInstance(); $attrs[2]->newInstance(); $attrs[3]->newInstance(); $attrs[4]->newInstance();