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 75#[Attribute] 76class A4 { } 77 78$ref = new \ReflectionFunction(#[A4(1)] function () { }); 79 80try { 81 $ref->getAttributes()[0]->newInstance(); 82} catch (\Error $e) { 83 var_dump('ERROR 5', $e->getMessage()); 84} 85 86echo "\n"; 87 88class A5 { } 89 90$ref = new \ReflectionFunction(#[A5] function () { }); 91 92try { 93 $ref->getAttributes()[0]->newInstance(); 94} catch (\Error $e) { 95 var_dump('ERROR 6', $e->getMessage()); 96} 97 98?> 99--EXPECTF-- 100string(2) "A1" 101string(4) "test" 102int(50) 103 104string(7) "ERROR 1" 105string(%d) "Too few arguments to function A1::__construct(), 0 passed in %s005_objects.php on line 26 and at least 1 expected" 106 107string(7) "ERROR 2" 108string(%d) "A1::__construct(): Argument #1 ($name) must be of type string, array given, called in %s005_objects.php on line 36" 109 110string(7) "ERROR 3" 111string(30) "Attribute class "A2" not found" 112 113string(7) "ERROR 4" 114string(48) "Attribute constructor of class A3 must be public" 115 116string(7) "ERROR 5" 117string(69) "Attribute class A4 does not have a constructor, cannot pass arguments" 118 119string(7) "ERROR 6" 120string(55) "Attempting to use non-attribute class "A5" as attribute" 121