0

I'm having an issue in type-checking some methods of a trait. I'm using a sort of facade-pattern and my aim would be to inject some methods of a facade in other classes through a trait that has generic declared methods with the return type of the class that uses the trait.

This is the structure of my project:

/**
 * This class has the methods I would like to inject in other classes with a trait.
 * The return type of these methods should refer to the class that uses the trait.
 *
 * @template T
 */
class MyFacade {
  /**
   * @return T
   */
  public function facadeMethod() { ... }
}
/**
 * This the trait that injects methods in those classes that use it. 
 * The return type of these methods has to be the type of the facade, 
 * infering in it the type of the class.
 */
trait MyTrait {
  /**
   * @return MyFacade<static>
   */
  static function traitMethod() { ... }
}
/**
 * This class uses the trait.
 */
class MyClass {
  use MyTrait;
}

So when i write:

$result = MyClass::traitMethod()->facadeMethod();

I would like $result to be of type MyClass, but the IDE says that the type is actually MyTrait, so it suggests me properties and methods of all the classes that use the trait, and this is useless for me.

Can someone help me with it?

3
  • Does your IDE support adding this information through for example annotations? Commented Oct 6, 2023 at 8:14
  • Which IDE says that? Point is, this may well depend on that, and less on the code you wrote. What does e.g. Psalm or PHPStan think of this? Commented Oct 6, 2023 at 8:14
  • The IDE is PhpStorm and usually works fine for type-checking with PhpDoc. If I use static::class inside the @return MyFacade<?> of the trait's method it doesn't work because of bad syntax. Returning $this on facadeMethod actually suggests the properties of MyFacade, but I'd need MyClass properites instead Commented Oct 6, 2023 at 9:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.