0

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

autocomplete-for-inheritance

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

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

0

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())
;

enter image description here

LazyOne
  • 158,824
  • 45
  • 388
  • 391
  • Thank you for your answer! I've corrected the question, thanks for the remarks! Yes, `@return $this` solves the problem. It would be nice to find a solution without PHPDoc for setters, but in this case, your' right, the IDE will use the defined return type, and it's `self` -- and `self` is static. – automatix Jun 20 '18 at 19:33
  • Generally speaking, I would expect IDE to treat `self` in `: self` as `$this` (which means "current or child class"). But right now it treats it as current class only (just like `@return self` is treated in PHPDoc). I cannot say why exactly it's done like that .. but it is what we have right now. If you think it's a bug .. or just want a better default interpretation -- feel free to file a ticket at https://youtrack.jetbrains.com/issues/WI – LazyOne Jun 20 '18 at 19:37