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

reply all(1)
P粉107991030

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();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!