1--TEST-- 2Attributes can be converted into objects. 3--FILE-- 4<?php 5 6#[Attribute(Attribute::TARGET_FUNCTION)] 7class A1 8{ 9 public string $name; 10 public int $ttl; 11 12 public function __construct(string $name, int $ttl = 50) 13 { 14 $this->name = $name; 15 $this->ttl = $ttl; 16 } 17} 18 19$ref = new \ReflectionFunction(#[A1('test')] function () { }); 20 21foreach ($ref->getAttributes() as $attr) { 22 $obj = $attr->newInstance(); 23 24 var_dump(get_class($obj), $obj->name, $obj->ttl); 25} 26 27echo "\n"; 28 29$ref = new \ReflectionFunction(#[A1] function () { }); 30 31try { 32 $ref->getAttributes()[0]->newInstance(); 33} catch (\ArgumentCountError $e) { 34 var_dump('ERROR 1', $e->getMessage()); 35} 36 37echo "\n"; 38 39$ref = new \ReflectionFunction(#[A1([])] function () { }); 40 41try { 42 $ref->getAttributes()[0]->newInstance(); 43} catch (\TypeError $e) { 44 var_dump('ERROR 2', $e->getMessage()); 45} 46 47echo "\n"; 48 49$ref = new \ReflectionFunction(#[A2] function () { }); 50 51try { 52 $ref->getAttributes()[0]->newInstance(); 53} catch (\Error $e) { 54 var_dump('ERROR 3', $e->getMessage()); 55} 56 57echo "\n"; 58 59#[Attribute] 60class A3 61{ 62 private function __construct() { } 63} 64 65$ref = new \ReflectionFunction(#[A3] function () { }); 66 67try { 68 $ref->getAttributes()[0]->newInstance(); 69} catch (\Error $e) { 70 var_dump('ERROR 4', $e->getMessage()); 71} 72 73echo "\n"; 74 75class A5 { } 76 77$ref = new \ReflectionFunction(#[A5] function () { }); 78 79try { 80 $ref->getAttributes()[0]->newInstance(); 81} catch (\Error $e) { 82 var_dump('ERROR 6', $e->getMessage()); 83} 84 85?> 86--EXPECTF-- 87string(2) "A1" 88string(4) "test" 89int(50) 90 91string(7) "ERROR 1" 92string(%d) "Too few arguments to function A1::__construct(), 0 passed in %s005_objects.php on line 26 and at least 1 expected" 93 94string(7) "ERROR 2" 95string(%d) "A1::__construct(): Argument #1 ($name) must be of type string, array given, called in %s005_objects.php on line 36" 96 97string(7) "ERROR 3" 98string(30) "Attribute class "A2" not found" 99 100string(7) "ERROR 4" 101string(51) "Call to private A3::__construct() from global scope" 102 103string(7) "ERROR 6" 104string(55) "Attempting to use non-attribute class "A5" as attribute" 105