How can I let phpstan know that a string contains the name of a class of a given type? #5019
-
I've got some code that uses the scope resolution operator (Paamayim Nekudotayim, For example, here is an interface interface ITransformer
{
public static function Transform( string $theInput, bool &$theErrorEncountered ) : string;
} and a class implementing it class Transformer implements ITransformer
{
public static function Transform( string $theInput, bool &$theErrorEncountered ) : string
{
if ( $theInput === 'invalid' )
{
$theErrorEncountered = true;
return '';
}
return strtoupper( trim($theInput) );
}
} The name of a class implementing $transformer = 'Transformer';
$input = ' asdasda asdasd ';
$error = false;
// At this point, I know that $transformer is the name of a class implementing `ITransformer`
// How can I tell phpstan that?
$output = $transformer::Transform( $input, $error ); At present, phpstan is not understanding that See, for example: https://phpstan.org/r/ada88746-fd60-4187-abfc-046ed28bf750 PHPStan thinks that How can I tell phpstan that Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hi, Which means that for your original example to work, a slight change needs to be done in PHPStan internals, around this place: https://github.com/phpstan/phpstan-src/blob/18f8473fa5c8e957f5e24d25961160ac89afd506/src/Analyser/NodeScopeResolver.php#L2070 (same logic needs to be executed in the Feel free to tackle this problem, or open a bug report. |
Beta Was this translation helpful? Give feedback.
Hi,
this works: https://phpstan.org/r/bdd8200a-b3cb-49c6-8c09-675aca255411
Which means that for your original example to work, a slight change needs to be done in PHPStan internals, around this place: https://github.com/phpstan/phpstan-src/blob/18f8473fa5c8e957f5e24d25961160ac89afd506/src/Analyser/NodeScopeResolver.php#L2070 (same logic needs to be executed in the
$expr->name instanceof Expr
branch as here).Feel free to tackle this problem, or open a bug report.