mirror of
https://github.com/danog/psalm.git
synced 2024-11-30 04:39:00 +01:00
docs: Add information on pure-callables to documentation (see #9132)
This commit is contained in:
parent
5d6dff9069
commit
a1ad738889
@ -25,3 +25,34 @@ function delayedAdd(int $x, int $y) : Closure {
|
||||
$adder = delayedAdd(3, 4);
|
||||
echo $adder(true);
|
||||
```
|
||||
|
||||
## Pure callables
|
||||
|
||||
For situations where the `callable` needs to be pure or immutable, the subtypes `pure-callable` and `pure-Closure` are also available.
|
||||
|
||||
This can be useful when the `callable` is used in a function marked with `@psalm-pure` or `@psalm-mutation-free`, for example:
|
||||
|
||||
```php
|
||||
<?php
|
||||
/** @psalm-immutable */
|
||||
class intList {
|
||||
/** @param list<int> $items */
|
||||
public function __construct(private array $items) {}
|
||||
|
||||
/**
|
||||
* @param pure-callable(int, int): int $callback
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function walk(callable $callback): int {
|
||||
return array_reduce($this->items, $callback, 0);
|
||||
}
|
||||
}
|
||||
|
||||
$list = new intList([1,2,3]);
|
||||
|
||||
// This is ok, as the callable is pure
|
||||
echo $list->walk(fn (int $c, int $v): int => $c + $v);
|
||||
|
||||
// This will cause an InvalidArgument error, as the closure calls an impure function
|
||||
echo $list->walk(fn (int $c, int $v): int => $c + random_int(1, $v));
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user