简体   繁体   中英

How to get the autocomplition working correctly for inherited methods in PhpStorm?

There are two classes defined as follows:

class Foo
{
    private $aaa;
    public function setAaa(Aaa $aaa): self
    {
        $this->aaa = $aaa;
        return $this;
    }
}

class Bar extends Foo
{
    private $bbb;
    public function setBbb(Bbb $bbb): self
    {
        $this->bbb = $bbb;
        return $this;
    }
}

So here "fluent" setters are used. But PhpStorm seems to ignore this and displays a warning:

$bar = (new Bar())
    ->setAaa(new Aaa())
    ->setAaa(new Bbb())
;

Method 'setBbb' not found in ...\\Foo

继承自动完成

Is there a way to get the autocompletion working as expected ins such cases?

First of all -- fix your code sample -- make it real and not some PHP-looking chunk of text.

  • class Bar extends -- extends what?
  • what is setAaa() method?
  • what is setBbb() method? Your code sample does not have it.

Anyway ... as for the actual question, after making all the changes so it looks like real PHP code...

Use PHPDoc and ensure that it says @return $this . Right now it interprets self in : self part as specific class (which is Foo ) ... and setPropertyBbb() is obviously NOT available in Foo class. By specifying @return $this you make it fluent in IDE eyes.

<?php

class Foo
{
    private $aaa;

    /**
     * My super method
     *
     * @param Aaa $aaa
     * @return $this
     */
    public function setPropertyAaa(Aaa $aaa): self
    {
        $this->aaa = $aaa;
        return $this;
    }
}

class Bar extends Foo 
{
    private $bbb;
    public function setPropertyBbb(Bbb $bbb): self
    {
        $this->bbb = $bbb;
        return $this;
    }
}

$bar = (new Bar())
    ->setPropertyAaa(new Aaa())
    ->setPropertyBbb(new Bbb())
;

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM