Skip to content

Commit

Permalink
Merge pull request #8135 from ThomasLandauer/patch-1
Browse files Browse the repository at this point in the history
PossiblyNullArgument: Adding common problem cases and possible solutions
  • Loading branch information
orklah committed Jun 21, 2022
2 parents 710768e + 3bca297 commit 29a2162
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion docs/running_psalm/issues/PossiblyNullArgument.md
Expand Up @@ -5,6 +5,44 @@ Emitted when calling a function with a value that’s possibly null when the fun
```php
<?php

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

## Common Problem Cases

### Using a Function Call inside `if`

```php
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:
```php
$catName = $cat->getName();
if (is_string($catName) {
foo($catName);
}
unset($catName);
```
* Add [`@psalm-mutation-free`](../../annotating_code/supported_annotations.md#psalm-mutation-free) to the declaration of the function

### Calling Another Function After `if`

```php
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`](../../annotating_code/supported_annotations.md#psalm-mutation-free) to the declaration of the other function (here: `changeCat()`) too
* Use a variable: See above

0 comments on commit 29a2162

Please sign in to comment.