kushj
0
Q:

php 8 attributes

      /*
      in MyClassContainingAttributesOnMethods:
      */
      class MyClassContainingAttributesOnMethods
      {
      	#[MyAttribute]
		#[MyOtherAttribute("someArgument", 1234, "someOtherArguments")]
		public function someFunction() {...}

      }
      
      /*
      in MyOtherAttribute:
      */
	  #[Attribute]
      class MyOtherAttribute
      {  
      	public function __construct(string $arg1, int $arg2, string $arg3) {...}
      }
      
	  /*
      In app:
      */
       $reflectionClass = new ReflectionClass(MyClassContainingAttributesOnMethods::class);

        foreach($reflectionClass->getMethods() as $method) {
            $attributes = $method->getAttributes(MyAttribute::class);
            if(count($attributes) == 1) {
                $method = MyClassContainingAttributesOnMethods::class."::".$method->getName();
                $arguments = [];
                foreach($method->getAttributes(MyOtherAttribute::class) as $otherArgument) {
                    $otherArg = $otherArgument->newInstance();
                    $arguments[$otherArg->argument] = self::require($otherArgument->serviceId);
                }

                $result = $method(...$arguments);
            }
        }
1

New to Communities?

Join the community