1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-15 02:47:02 +01:00
psalm/docs/running_psalm/issues/PossiblyNullArgument.md
2022-06-21 22:45:45 +02:00

1.2 KiB
Raw Blame History

PossiblyNullArgument

Emitted when calling a function with a value thats possibly null when the function does not expect it

<?php

function foo(string $s): void {}
foo(rand(0, 1) ? "hello" : null);

Common Problem Cases

Using a Function Call inside if

if (is_string($cat->getName()) {
    foo($cat->getName());
}

This fails since it's not guaranteed that subsequent calls to $cat->getName() always give the same result.

Possible Solutions

  • Use a variable:
    $catName = $cat->getName();
    if (is_string($catName) {
        foo($catName);
    }
    unset($catName);
    
  • Add @psalm-mutation-free to the declaration of the function

Calling Another Function After if

if (is_string($cat->getName()) {
    changeCat();
    foo($cat->getName());
}

This fails since psalm cannot know if changeCat() does actually modify $cat.

Possible Solutions

  • Add @psalm-mutation-free to the declaration of the other function (here: changeCat()) too
  • Use a variable: See above