Is there any why to make my IDE (actually PHPStorm) understand that:
$student->setName('Marco');
Will return an instance of Student
, without redefining setName()
in the subclass (only for adding PHPDoc comments)?
class Person
{
private $name;
/**
* @param string $name
* @return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
class Student extends Person { }
You can return $this instead of person in your docblock
you have to overwrite your method tag as comment like this
/**
* @method Student setName($name)
*/
class Student extends Person { }
In my experience, I've found it helpful to use a combination approach. My IDE (IntelliJ IDEA with PHP plug-in) complained that my fluent methods were returning $this
when that value was used as a parameter to another method call later. By changing the PHPDoc comment to this:
/**
* @param string $name
* @return $this|Person
*/
The IDE was happier and the PHPDoc is more informative for the user.
Incidentally, by saying the method returns $this
in the PHPDoc, it's a very good indication that the method is implementing a fluent interface. Saying it returns Person
, while technically accurate, doesn't necessarily indicate fluency. For example, a method that creates a new Person
object and returns it could also use that same annotation, but it wouldn't be fluent.