Since this thread is well indexed in search engines and there's no valid answer here, I would like to leave a note how to correctly annotate an anonymous function in terms of its parameters, as well as the output.
This way of documenting anonymous functions in PHP is understood by modern IDEs (like PHPStorm
, as well as static analysis tools like PHPStan
or Psalm
.)
Imagine a function that accepts a callable. The callable is expected to return an array of users based on some filter criteria provided to it by the caller. In this case let's pass an array of user IDs expected as the first argument and some additional state criteria in the second.
Here's a valid example of this function including the doc block:
/**
* @param callable(array<int>,array<string,mixed>):array<User> $userProvider
*
* @return array<array{id:int, name:string}>
*/
function usersToArray(callable $userProvider): array
{
$result = [];
foreach ($userProvider([1, 2], ['active' => true]) as $user) {
// PHPStorm knows that $user is a User entity
$result[] = [
'id' => $user->getId(),
'name' => $user->getName(),
];
}
return $result;
}
Let's break down the callable's annotation:
callable(array<int>,array<string,mixed>):array<User>
It describes:
- a callable
callable(…)
- that requires two arguments:
- an array of integers
array<int>
- an array of some arguments indexed by a string column
array<string,mixed>
- it returns an array of
User
entities array<User>