Return type for methods of descendant classes? #4321
-
I've created a simplified version of the code I'm running through PHPStan: class Queryer {
public $results;
/**
* @return self
*/
public function get_record($q): self
{
$this->results = send_query($q);
return $this;
}
}
class UserQueryer extends Queryer {
/**
* @return self
*/
public function get_record($q): self
{
$this->results = send_query($q);
$this->somethingOverridden = 'whatever';
return $this;
}
} Basically, I have a generic database-querying class with a method "get_record" that returns the object itself, so methods can be chained. Then I have class-specific inheritors of the class, like "UserQueryer" which might override the get_record method, as above. If I set the return type of UserQueryer::get_record to "self" I get something like:
Since the "self" type declaration should indicate an How could I type hint the UserQueryer method correctly in this situation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi, this isn't so much related to PHPStan as to PHP itself. Your code doesn't work on PHP 7.3 and lower: https://3v4l.org/IVs47 It's because on PHP 7.4 and later this RFC allowed this usecase: https://wiki.php.net/rfc/covariant-returns-and-contravariant-parameters |
Beta Was this translation helpful? Give feedback.
Hi, this isn't so much related to PHPStan as to PHP itself. Your code doesn't work on PHP 7.3 and lower: https://3v4l.org/IVs47
It's because on PHP 7.4 and later this RFC allowed this usecase: https://wiki.php.net/rfc/covariant-returns-and-contravariant-parameters