【问题标题】:What does PHPDoc "static" return type signify here?PHPDoc“静态”返回类型在这里表示什么?
【发布时间】:2015-03-27 12:39:59
【问题描述】:

我正在处理一个由 Doctrine 管理的实体的 Symfony 项目。以下是我的实体的代码:

class User {
    /**
     * @ORM\OneToMany(targetEntity="Appointment", mappedBy="user")
     */
    private $appointments;

    /**
     * Get appointments
     *
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function getAppointments()
    {
        return $this->appointments;
    }

    /**
     * Get appointments at a specified date
     *
     * @param \DateTime $date
     * @return \Doctrine\Common\Collections\Collection|static
     */
    public function getAppointmentsAtDate(\DateTime $date) {
        $allAppointments = $this->getAppointments();

        $criteria = Criteria::create()->where(/* some clever filtering logic goes here */);

        return $allAppointments ->matching($criteria);
    }
}

getAppointments 是由 Doctrine 自动生成的。 getAppointmentsAtDate 方法是我自己实现的。该方法的 PHPDoc 标头由 PhpStorm 自动生成。

我无法理解的是我的自定义方法的返回类型中的 static 关键字。

根据我对PHPDoc types 的理解,static 表示此方法返回调用它的类的实例,在本例中为User 实例。

但是,我看不出此方法如何返回 User 实例或 Collection 实例以外的任何内容。

那么static 关键字在这里是什么意思?我对关键字的理解有问题吗?还是 PhpStorm 的自动生成的文档标题完全错误?

【问题讨论】:

    标签: php symfony doctrine-orm phpstorm phpdoc


    【解决方案1】:

    我查看了matching function 的教义来源,这是返回类型:

    return new static($filtered);
    

    Phpstorm 可能解析了学说源码,在匹配函数中看到了 return static 语句。

    【讨论】:

    • 好的,但是这意味着生成的返回类型不正确,对吧?因为matching 函数返回一个static 对象,它是Collection 的某个子类,所以我的方法将始终返回一个Collection(或子类),但绝不会返回User 或子类。
    • 是的,解释不正确!您应该删除文档中的|static
    【解决方案2】:

    你对static关键字的理解是正确的。

    您的代码:

    return $allAppointments ->matching($criteria);
    

    Doctrine\Common\Collections\ArrayCollection类返回匹配函数的结果,该类返回:

    return new static($filtered);
    

    正如您在文件 ArrayCollection.php 的第 385 行看到的那样

    这可能是 PHPStorm 推断出可能的返回类型的地方。代码:

    new static()
    

    在 PHPStorm 看来会返回一个静态类的新实例。可能不是正确的解释,但您应该看到自动化系统不一定知道以下之间的区别:

    new someclass();
    // and
    new static();
    

    【讨论】:

      【解决方案3】:

      您对静态关键字的理解听起来是正确的。 matching 方法的 PHPDoc 说它返回 Collection。在我看来,PhpStorm 犯了一个错误。也许您在生成代码后对其进行了一些更改?

      【讨论】:

      • 为了检验你的假设,我刚刚删除了文档标题,它仍然以相同的返回类型重新生成。
      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 2012-09-08
      • 2013-05-21
      • 1970-01-01
      相关资源
      最近更新 更多