php 8 attributes

Solutions on MaxInterview for php 8 attributes by the best coders in the world

showing results for - "php 8 attributes"
Riccardo
08 Feb 2017
1      /*
2      in MyClassContainingAttributesOnMethods:
3      */
4      class MyClassContainingAttributesOnMethods
5      {
6      	#[MyAttribute]
7		#[MyOtherAttribute("someArgument", 1234, "someOtherArguments")]
8		public function someFunction() {...}
9
10      }
11      
12      /*
13      in MyOtherAttribute:
14      */
15	  #[Attribute]
16      class MyOtherAttribute
17      {  
18      	public function __construct(string $arg1, int $arg2, string $arg3) {...}
19      }
20      
21	  /*
22      In app:
23      */
24       $reflectionClass = new ReflectionClass(MyClassContainingAttributesOnMethods::class);
25
26        foreach($reflectionClass->getMethods() as $method) {
27            $attributes = $method->getAttributes(MyAttribute::class);
28            if(count($attributes) == 1) {
29                $method = MyClassContainingAttributesOnMethods::class."::".$method->getName();
30                $arguments = [];
31                foreach($method->getAttributes(MyOtherAttribute::class) as $otherArgument) {
32                    $otherArg = $otherArgument->newInstance();
33                    $arguments[$otherArg->argument] = self::require($otherArgument->serviceId);
34                }
35
36                $result = $method(...$arguments);
37            }
38        }
39