Can I indicate dynamic type returned to PhpStorm?

♀尐吖头ヾ 提交于 2020-01-06 03:32:04

问题


I have 3 classes like :

class Foo
{
    static function test()
    {
       return new static();
    }
}

class Bar extends Foo
{}

class Baz extends Foo
{}

Now if call :

$var = Bar::test();

I want PhpStorm to identify $var as the called_class, here: Bar.

But, if I do $var = Baz::test(); $var is Baz instance.

How can I get the dynamic called_class to indicate to PhpStorm what type is returned?

I there a syntax like

/** @return "called_class" */

to help PhpStorm and indicate the type?


回答1:


First you have an error in your static function. You can not use

 return $this;

as the static call will not create any instance. So you have to create a new instance.

class Foo
{
    public static function test()
    {
        return new static();
    }
}

The static keyword will instantiate a new instance of the class itself.

class Bar extends Foo
{
    public function fooBar(){}
}

class Baz extends Foo
{
    public function fooBaz(){}
}

i just added the foo functions to show you that phpStorm now will correctly find the source.

$var = Bar::test();
$var->fooBar();

$var is now an instance of Bar

$var2 = Baz::test();   
$var2->fooBaz();

$var2 is now an instance of Baz



来源:https://stackoverflow.com/questions/29520850/can-i-indicate-dynamic-type-returned-to-phpstorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!