gremo
gremo

Reputation: 48899

PHPDoc for fluent interface in subclass?

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 { }

Upvotes: 3

Views: 1060

Answers (3)

Mr. Lance E Sloan
Mr. Lance E Sloan

Reputation: 3387

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.

Upvotes: 0

Chris
Chris

Reputation: 8968

You can return $this instead of person in your docblock

Upvotes: 5

silly
silly

Reputation: 7887

you have to overwrite your method tag as comment like this

/**
 * @method Student setName($name)
 */
class Student extends Person { }

Upvotes: 5

Related Questions