Skip to content

Commit f7bea8d

Browse files
committed
rememberPossiblyImpureFunctionValues docs
1 parent 5fe9a5d commit f7bea8d

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

website/src/_posts/remembering-and-forgetting-returned-values.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ if (impureFunction()) {
5858
}
5959
```
6060

61+
If the `impureFunction()` didn't have the `/** @phpstan-impure */` annotation, the value would be remembered for further calls. If you want to change this behaviour and don't want to assume functions returning a value are pure by default, set `rememberPossiblyImpureFunctionValues: false` in your configuration file (available in PHPStan 1.8.0). See [Config Reference](/config-reference#rememberpossiblyimpurefunctionvalues) for more details.
62+
6163
If you call an impure method on an object that already has a remembered method value, it will be forgotten:
6264

6365
```php

website/src/config-reference.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,45 @@ public function setFoo(int $foo): void
410410

411411
When set to `true`, it reports use of dynamic properties as undefined.
412412

413+
### `rememberPossiblyImpureFunctionValues`
414+
415+
<div class="text-xs inline-block border border-green-600 text-green-600 bg-green-100 rounded px-1 mb-4">Available in PHPStan 1.8.0</div>
416+
417+
**default**: `true`
418+
419+
By default, PHPStan considers all functions that return a value to be pure. That means that second call to the same function in the same scope will return the same narrowed type:
420+
421+
```php
422+
public function getName(): string
423+
{
424+
return $this->name;
425+
}
426+
427+
if ($this->getName() === 'Foo') {
428+
echo $this->getName(); // still 'Foo'
429+
}
430+
```
431+
432+
This is a sane default in case of getters but sometimes we have a function that can return different values based on a global state like a random number generator, database, or time.
433+
434+
```php
435+
public function getRandomNumber(): int
436+
{
437+
return rand();
438+
}
439+
440+
if ($this->getRandomNumber() === 4) {
441+
echo $this->getRandomNumber(); // it's not going to be 4 but PHPStan will think it is
442+
}
443+
```
444+
445+
You can mark `getRandomNumber()` with `/** @phpstan-impure */` but if you have many functions like this in your codebase and don't want to assume functions return the same value when called multiple times, you can set `rememberPossiblyImpureFunctionValues` to `false`:
446+
447+
```yaml
448+
parameters:
449+
rememberPossiblyImpureFunctionValues: false
450+
```
451+
413452
Exceptions
414453
------------
415454

0 commit comments

Comments
 (0)