🪧 Generics, covariance, and @method
#10895
-
Hello, I am afraid to open here a discussion which is already answered somewhere. IntroductionPHPStan may not support what I am looking to do, and that's OK. What I want to doI have a bunch of classes with a signature like that where class MyClass {
public function foo(ZZZRequest $request): void {
// ...
}
} All these Because of contravariance, I don't want to declare the foo method into the interface. interface MyClassInterface {
public function foo(RequestInterface $request): void;
} I was then trying to play around with the
What I tried so farhttps://phpstan.org/r/523f2735-d2ca-420a-9c46-8089ff42aa03 // ━━━━━━━━━ Interface declaration ━━━━━━━━━
/**
* @template-covariant T of object
*
* @method void test(T $k)
*/
interface IFace { }
// ━━━━━━━━━ Expected SUCCESS ━━━━━━━━━
/**
* @implements IFace<stdClass>
*/
class Working implements IFace {
public function test(stdClass $k): void { }
}
// ━━━━━━━━━ Expected FAILURE ━━━━━━━━━
/**
* @implements IFace<int>
*/
class PhpdocNotCovariant implements IFace {
public function test(int $k): void { }
}
/**
* @implements IFace<stdClass>
*/
class PhpdocCovariantButNotReal implements IFace {
public function test(int $k): void { }
} Warning You can see that when you respect the phpdoc generic covariant type, the method type is not checked by PHPStan. That's may be normal, but it is a bit confusing. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Generics provide a way how to solve this parameter contravariance problem. It's described here: https://phpstan.org/blog/generics-in-php-using-phpdocs#these-rules-are-useful%2C-but-sometimes-limiting In your case it'd look like this: https://phpstan.org/r/ae194a3c-529c-44f5-a0bc-566af710a14d |
Beta Was this translation helpful? Give feedback.
Generics provide a way how to solve this parameter contravariance problem. It's described here: https://phpstan.org/blog/generics-in-php-using-phpdocs#these-rules-are-useful%2C-but-sometimes-limiting
In your case it'd look like this: https://phpstan.org/r/ae194a3c-529c-44f5-a0bc-566af710a14d