Type deduction for callbacks in array functions

Some time ago PhpStorm started recognizing types for parameters in callbacks used with functions like array_filter. E.g. if I write something like:

/** @var int[] $a */
$a = [1, 2, 3, 4];
$odds = array_filter($a, fn($i) => $i % 2);

Then IDE will deduce that $i inside the callback has type int. Which is pretty helpful!

Unfortunately, I can't see how to make it work for used-defined function. E.g. I have a function 'array_any':

* @template T
* @param array<T> $array
* @param callable(T): bool $predicate
* @return bool
function array_any(array $array, callable $predicate): bool

Which tells whether the array contains a value sufficing the predicate. If I use this one:

/** @var int[] $a */
$a = [1, 2, 3, 4];
$hasOdds = array_any($a, fn($i) => $i % 2);

Then IDE won't make any assumptions about $i inside of the callback.

So, my question is: can I 'explain' to IDE somehow, that my function can use the same kind of type deduction it uses for 'array_filter'? Or maybe PhpStorm will start deducing that from templates in PhpDoc someday?

1 comment

There's nothing you can do to work this around yourself - we have to support it on our side.
Thank you for the suggestion! I extracted this as WI-73911.


Please sign in to leave a comment.