Skip to content

Commit 1a121e8

Browse files
phpstan-botclaude
andcommitted
Do not warn about ?? on non-$this typed properties without default value
Properties declared as `public int $i;` (without a default value) can be uninitialized when accessed on external objects, so using ?? on them is valid. Only warn when the property has a default value (guaranteed initialized). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent d282a5f commit 1a121e8

4 files changed

Lines changed: 15 additions & 9 deletions

File tree

src/Rules/IssetCheck.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,11 @@ static function (Type $type) use ($typeMessageCallback): ?string {
197197

198198
return null;
199199
}
200+
201+
$nativeReflection = $propertyReflection->getNativeReflection();
202+
if ($nativeReflection !== null && !$nativeReflection->getNativeReflection()->hasDefaultValue()) {
203+
return $this->checkUndefined($expr->var, $scope, $operatorDescription, $identifier);
204+
}
200205
}
201206
}
202207

tests/PHPStan/Rules/Variables/IssetRuleTest.php

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,6 @@ public function testNativePropertyTypes(): void
210210
'Property IssetNativePropertyTypes\Foo::$isAssignedBefore (int) in isset() is not nullable.',
211211
20,
212212
],
213-
[
214-
'Property IssetNativePropertyTypes\Foo::$canBeUninitialized (int) in isset() is not nullable.',
215-
22,
216-
],
217213
]);
218214
}
219215

tests/PHPStan/Rules/Variables/NullCoalesceRuleTest.php

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,6 @@ public function testCoalesceRule(): void
113113
131,
114114
],
115115
];
116-
$errors[] = [
117-
'Property ReflectionClass<object>::$name (class-string<object>) on left side of ?? is not nullable.',
118-
136,
119-
];
120116
$errors[] = [
121117
'Variable $foo on left side of ?? is never defined.',
122118
141,
@@ -379,7 +375,7 @@ public function testBug14393(): void
379375
$this->analyse([__DIR__ . '/data/bug-14393.php'], [
380376
[
381377
'Property Bug14393\MyClass::$i (int) on left side of ?? is not nullable.',
382-
12,
378+
17,
383379
],
384380
]);
385381
}

tests/PHPStan/Rules/Variables/data/bug-14393.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,15 @@ class MyClass
77
public int $i = 10;
88
}
99

10+
class MyClassUninitialized
11+
{
12+
public int $i;
13+
}
14+
1015
$o = new MyClass();
1116

1217
var_dump($o->i ?? -1);
18+
19+
$o2 = new MyClassUninitialized();
20+
21+
var_dump($o2->i ?? -1);

0 commit comments

Comments
 (0)