Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does PHPDoc "static" return type signify here?

I am working on a Symfony project with entities managed by Doctrine. The following is code from my entity:

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 is auto-generated by Doctrine. The getAppointmentsAtDate method was implemented by myself. The method's PHPDoc header was auto-generated by PhpStorm.

What I cannot understand is the static keyword in my custom method's return type.

From my understanding of the PHPDoc types static signifies that this method returns an instance of the class on which it was called, in this case a User instance.

However, I fail to see how this method could ever return a User instance or anything other than an instance of Collection.

So what does the static keyword mean here? Is my understanding of the keyword flawed? Or is PhpStorm's auto-generated documentation header simply wrong?

like image 756
Chris Avatar asked Jan 28 '15 14:01

Chris


2 Answers

I have looked at the source of doctrine for the matching function and here is the return type :

return new static($filtered);

Phpstorm probably parsed the doctrine source and saw the return static statement in the matching function.

like image 134
Nico Avatar answered Nov 02 '22 07:11

Nico


Your understanding of the static keyword is correct.

Your code:

return $allAppointments ->matching($criteria);

Returns the results of the matching function, from the Doctrine\Common\Collections\ArrayCollection class, which returns:

return new static($filtered);

As you can see on line 385, of the file ArrayCollection.php

Which is probably where PHPStorm deduced the possible return type. The Code:

new static()

Would appear to PHPStorm to be returning a new instance of a static class. Probably not the correct interpretation, but you should see how an automated system would not necessarily know the difference between:

new someclass();
// and
new static();
like image 2
bubba Avatar answered Nov 02 '22 07:11

bubba