Re: array_reduce callback key
| From: | Larry Garfield | Date: | Wed, 17 Jul 2024 14:01:55 +0000 |
| Subject: | Re: array_reduce callback key | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-124458@lists.php.net to get a copy of this message | ||
On Wed, Jul 17, 2024, at 9:01 AM, Bilge wrote:
> On 17/07/2024 01:41, Levi Morrison wrote:
>> Adding arguments to a function can mess up internal callbacks, btw, so I don't like
>> modifying the
>> existing function.
> Which internal callbacks can be messed up by this change? They clearly
> aren't tested, as the build is passing.
>
> Cheers,
> Bilge
There's a number of issues here.
PHP-defined functions ignore excess arguments.
C-defined functions error on excess arguments.
A function with an optional second argument... may break if it gets passed an optional argument that
isn't aligned with its expectation. intval() is the usual example
(https://www.php.net/intval), but it would also impact something like trim(). If someone is using a
function with one param and one optional param as a callback right now, suddenly passing the key as
the second argument could cause all sorts of weirdness.
Similarly, if someone is using a single-param C-defined function as a callback right now, and
array_reduce() starts passing a second argument, it will fatal.
I ran into this issue while building Crell/fp, and my only solution (after swearing a lot) was to
just make two separate versions of every operation: One that passes the key and one that
doesn't. (cf: https://github.com/Crell/fp/blob/master/src/array.php)
The user has to pick the right one. That is, sadly, the only reliable solution, even if done in
the stdlib.
(Of course, the real solution is to introduce a separate map/dict type that has its own dedicated
API for map/filter/reduce, but now we're well out of scope... Using the same structure for
lists and maps is PHP's original sin.)
--Larry Garfield