Skip to content

Commit 7d4dcb5

Browse files
committed
Infer types of variables with dynamic name
1 parent 08e38e2 commit 7d4dcb5

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/Analyser/MutatingScope.php

+11-4
Original file line numberDiff line numberDiff line change
@@ -2000,12 +2000,19 @@ static function (Node $node, Scope $scope) use ($arrowScope, &$arrowFunctionImpu
20002000
);
20012001
}
20022002

2003-
if ($node instanceof Variable && is_string($node->name)) {
2004-
if ($this->hasVariableType($node->name)->no()) {
2005-
return new ErrorType();
2003+
if ($node instanceof Variable) {
2004+
if (is_string($node->name)) {
2005+
if ($this->hasVariableType($node->name)->no()) {
2006+
return new ErrorType();
2007+
}
2008+
2009+
return $this->getVariableType($node->name);
20062010
}
20072011

2008-
return $this->getVariableType($node->name);
2012+
$nameType = $this->getType($node->name);
2013+
if (count($nameType->getConstantStrings()) > 0) {
2014+
return TypeCombinator::union(...array_map(fn ($constantString) => $this->getVariableType($constantString->getValue()), $nameType->getConstantStrings()));
2015+
}
20092016
}
20102017

20112018
if ($node instanceof Expr\ArrayDimFetch && $node->dim !== null) {
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace Bug12398;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class Foo
8+
{
9+
10+
public function doFoo(string $foo): void
11+
{
12+
$bar = 'foo';
13+
assertType('string', $$bar);
14+
}
15+
16+
}

0 commit comments

Comments
 (0)