search

Home  >  Q&A  >  body text

Methods that return a subclass of a property @returns

<p>I have an abstract class <code>Foo</code> and an abstract builder <code>FooBuilder</code></p> <pre class="brush:php;toolbar:false;">abstract class Foo { } abstract class FooBuilder { protected Foo $model; /*** Return class instance * * @return Model //What is the correct return type? ?*/ public function get() { return $this->model; } } </pre> <p>I want to use the <code>get()</code> method in my child builder, but the IDE detects that the return type is a subclass, not abstract <code>Foo</code> ;. </p> <pre class="brush:php;toolbar:false;">class Bar extends Foo { } abstract class BarBuilder { public function __construct() { $this->model = new Bar(); } } $barBuilder = BarBuilder(); $bar = $barBuilder->get(); //The type is "Bar", but the IDE thinks it is "Foo" </pre> <p>Is there a way in PHPDoc to return the static type of a property instead of the class? Similar to <code>@return static($this->model)</code>? </p> <p>An example is the usage of Laravel's Eloquent in <code>SomeModel::find()</code>. The IDE knows that the type can be <code>SomeModel</code>. But <code>@return</code> only has <code>Model</code>. </p>
P粉310931198P粉310931198494 days ago567

reply all(1)I'll reply

  • P粉107991030

    P粉1079910302023-08-30 21:49:39

    You should use Foo as the return type in your example; but for fun, you can use a static return type to determine the subinstance, as shown below

    class Foo
    {
        /**
         * @return string
         */
        public function Iam(): string
        {
            return "hello";
        }
    }
    
    class Helper
    {
        /**
         * Return the class instance
         *
         * @return static
         */
        public static function get(): static
        {
            return new self();
        }
    }
    
    class FooBuilder extends helper
    {
        protected Foo $model;
    
        public function mememe()
        {
            echo "I am a method";
        }
    }
    
    class FooBuilder2 extends helper
    {
        protected Foo $model;
    
        public function xray()
        {
            echo "I am a method";
        }
    }
    
    $test = FooBuilder::get();
    $test->mememe();
    
    $test2 = FooBuilder2::get();
    $test2->xray();

    reply
    0
  • Cancelreply