-
-
Notifications
You must be signed in to change notification settings - Fork 862
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrect type expected when using static
with generics
#9407
Comments
The playground is telling you exactly what's wrong and links this article: https://phpstan.org/blog/whats-up-with-template-covariant |
Thanks for responding so quickly, @ondrejmirtes :) I did read the linked article, but (still) don't understand how/why this code needs a covariant template when the types it appears in are explicitly identical. Are you able to clarify what the trigger for this scenario is, please? I wasn't able to find documentation about PHPStan's evaluation of |
Actually, I think understand: <?php
/**
* @template T
*/
class R
{
public string $Class;
/**
* @var array<string,mixed>
*/
public array $Data = [];
/**
* @param class-string<T> $class
*/
public function __construct(string $class)
{
$this->Class = $class;
}
/**
* @param R<T> $r
* @return $this
*/
public function merge(R $r)
{
$this->Data += $r->Data;
return $this;
}
}
class A
{
/**
* @var R<static>
*/
public R $Value;
/**
* @return R<static>
*/
public static function getValue(): R
{
return new R(static::class);
}
/**
* @param R<static> $r
* @return R<static>
*/
public function changeValue(R $r): R
{
return $r;
}
/**
* @param R<static> $r
* @return $this
*/
public function withValue(R $r)
{
$this->Value = $r;
return $this;
}
/**
* @return $this
*/
public function doSomething()
{
return $this->withValue(static::getValue());
}
}
class B extends A {}
class C extends B {} (Playground here.) If I understand the semantics of PHPStan's Am I correct so far? If so, this implicit type narrowing is what was missing from my understanding, and explains why there are issues when values of type Anyway, assuming that's all working as intended, after adopting (Playground here.) |
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Bug report
With a generic like:
Using types like:
Leads to unresolvable errors like:
There's no way to annotate arguments and return values to make PHPStan believe
Rules<static(Entity)>
is expected and/or to indicateRules<Entity>
is returned.(The example makes it clearer.)
Code snippet that reproduces the problem
https://phpstan.org/r/4c2e877c-61a9-4fb0-9551-0684f402550f
Expected output
The example code shouldn't trigger any errors.
The text was updated successfully, but these errors were encountered: