Methods that return a subclass of a property @returns
P粉310931198
2023-08-29 23:28:05
<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>
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