NullPointerException
warning off by default experimentalGroup: Probable bugs · PhpStorm name: NullPointerExceptionInspection
A value that may be null (nullable object parameter, nullable local variable, call declared to return ?T/void) is dereferenced — property or method access, array access, invocation, clone, or passed to a parameter that rejects null — without a preceding null check. At runtime this is an "call to a member function on null"-style error.
Disabled by default (experimental upstream).
Example
php
<?php
class Node
{
public $value;
public function next(): ?Node { return null; }
public function take(Node $n) {}
public function walk(?Node $head, Node $tail = null, ?int $count = null, Node $plain, $loose = null)
{
$head->value = 1;
$head();
if ($head === null) {
return;
}
$head->value = 2;
$x = clone $tail;
$this->take($tail);
echo $tail->value ?? 'none';
if (isset($tail->value['a'])) {}
if ($tail) {
$tail->value = 3;
}
$plain->value = 4;
$loose->value = 5;
$count++;
}
public function chain()
{
$this->next()->next();
if ($this->next() != null) {
$this->next()->next();
}
$n = $this->next();
$n->next();
$n['k'];
$n = new Node();
$n->value = 0;
/** @var Node $m */
$m = $this->next();
$m->value = 1;
$cursor = $this->next();
while ($cursor !== null) {
$cursor = $cursor->next();
}
$probe = $this->next();
$probe->value = 1;
$probe = $probe->next();
}
public function refill(Node $left = null, ?Node $right, Node $up = null)
{
$left = $left ?: null;
$left->value = 1;
$right = $right ?? null;
$right->next();
$up = $up->next();
}
/** @param Node[] $list */
public function rewind(array $list)
{
foreach ($list as $item) {
$item = $item->next(); // declaring statement of local $item: right side exempt (E4)
$item->value = 1;
}
}
public function guarded(?Node $a, ?Node $b, ?Node $c)
{
static::assertNotNull($a);
Verify::that($b)->isObject()->notNull();
$this->that($c)->notNull();
return [$a->value, $b->value, $c->value];
}
}
function visit(?Node $item) {
\Assert\Assertion::notNull($item);
return $item->value;
}Reported:
- line 9: Possible null dereference.
- line 10: Possible null dereference.
- line 16: Possible null dereference.
- line 17: Possible null dereference.
- line 30: Possible null dereference.
- line 35: Possible null dereference.
- line 36: Possible null dereference.
- line 50: Possible null dereference.
- line 51: Possible null dereference.
- line 57: Possible null dereference.
- line 60: Possible null dereference.
- line 62: Possible null dereference.
- line 70: Possible null dereference.
Configure
In custos.json:
json
{
"rules": {
"NullPointerException": {
"enabled": true
}
}
}Suppress
Before the statement or declaration (or the first statement of the file), either of:
php
// @custos-ignore NullPointerException
/**
* @noinspection NullPointerExceptionInspection
*/