Search code examples
phpdesign-patternscastingphpstormintellisense

Type-casting problem while building fluid interface


For example we have the following abstract class

<?php
    class AbstractClass {
        public function setParam(): AbstractClass {}
    }

    class ConcreteClass extends AbstractClass {
        public function test():void {}
    }

When you'll try to use it like this

<?php
(new ConcreteClass())->setParam()->test();

Then after setParam we will see only setParam method, because setParam returns AbstractClass. I tried to mark setParam inside AbsractClass with PHP-doc @return self, but it doesn't work.

Are there any solutions of this problem?


Solution

  • To solve this problem you can use @return static PHP-doc attribute

    <?php
    
    class A {
       /** @return static */
       public function methodA(): A;
    }
    
    class B {
       /** @return static */
       public function methodB(): B;
    }
    
    (new B())->methodB()->methodA()->methodB();
    

    Everything in this example will be highlighted correctly.