PHPDoc for fluent interface in subclass?

假装没事ソ 提交于 2019-12-07 20:58:53

问题


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

回答1:


You can return $this instead of person in your docblock




回答2:


you have to overwrite your method tag as comment like this

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



回答3:


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.



来源:https://stackoverflow.com/questions/13563250/phpdoc-for-fluent-interface-in-subclass

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