3v4l.org

run code in 300+ PHP versions simultaneously
<?php #[Attribute(Attribute::TARGET_PROPERTY)] class SomeAttribute { } class Foo { public function __construct( #[SomeAttribute] public readonly string $someProperty, ) {} } $foo = new Foo('foobar'); $reflectedProperty = new ReflectionProperty($foo, 'someProperty'); var_dump($reflectedProperty->getAttributes()[0]->getName()); $reflectedMethod = new ReflectionMethod($foo, '__construct'); var_dump($reflectedMethod->getParameters()[0]->getAttributes()[0]->getName()); var_dump($reflectedProperty->getAttributes()[0]->newInstance()); var_dump($reflectedMethod->getParameters()[0]->getAttributes()[0]->newInstance());
Output for 8.1.11
string(13) "SomeAttribute" string(13) "SomeAttribute" object(SomeAttribute)#4 (0) { } Fatal error: Uncaught Error: Attribute "SomeAttribute" cannot target parameter (allowed targets: property) in /in/ElbFN:25 Stack trace: #0 /in/ElbFN(25): ReflectionAttribute->newInstance() #1 {main} thrown in /in/ElbFN on line 25
Process exited with code 255.

preferences:
159.16 ms | 1394 KiB | 8 Q