我正在与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
是由教义自动生成的。getAppointmentsAtDate
方法由我自己实现。该方法的 PHPDoc 标头由 PhpStorm 自动生成。
我无法理解的是自定义方法返回类型中的static
关键字。
根据我对 PHPDoc 类型的理解,static
表示此方法返回调用它的类的实例,在本例中为 User
实例。
但是,我看不出此方法如何返回User
实例或除Collection
实例以外的任何内容。
那么static
关键字在这里是什么意思呢?我对关键字的理解有缺陷吗?还是 PhpStorm 自动生成的文档标题完全错误?
我已经查看了matching
函数的学说来源,这里是返回类型:
return new static($filtered);
Phpstorm 可能解析了 doctrine 源代码,并在匹配函数中看到返回静态语句。
您对静态关键字的理解是正确的。
您的代码:
return $allAppointments ->matching($criteria);
从 Doctrine'Common'Collections'ArrayCollection
类返回匹配函数的结果,该类返回:
return new static($filtered);
正如您在第 385 行看到的,文件ArrayCollection.php
这可能是 PHPStorm 推断可能的返回类型的地方。守则:
new static()
在 PHPStorm 看来,它正在返回静态类的新实例。 可能不是正确的解释,但您应该看到自动化系统不一定知道以下两者之间的区别:
new someclass();
// and
new static();
你对静态关键字的理解听起来是正确的。matching
方法的 PHPDoc 说它返回 Collection
。在我看来,PhpStorm犯了一个错误。也许您在代码生成后对代码进行了一些更改?