Re: [PHP-DEV] A little syntactic sugar on array_* function calls?

This is only part of a thread. view whole thread
May 25, 2021 09:30 (Hans Henrik Bergan)
fwiw this can be implemented in userland, and i bet someone already made a
composer package for it ^^

On Tue, 25 May 2021 at 11:20, Karoly Negyesi <> wrote:

> Hi, > > I was wondering whether $array->map($somefunction) would be possible. I am > not a C programmer by any stretch but reading ZEND_VM_HOT_OBJ_HANDLER(112 > it seems to me it should be quite easy (famous last words) to find out if > object is an array and if so then > > 1. prepend the string array_ before the method name > 2. based on a small lookup table move the "object" to the right place -- > either first argument or second. > 3. do a function call instead of a method call. > > Regarding #2 by default it's the first: > > $array->flip() becomes array_flip($array) > $array->column($column_key, $index_key) becomes array_column($array, > $column_key, $index_key) > $array->merge($array2, $array3) becomes array_merge($array, $array2, > $array3) > > There'd be a small list of methods/functions where it's the second, for > example: > > $array->map($fn) becomes array_map($fn, $array) > $array->search($needle, $strict) becomes array_search($needle, $array, > $strict) > $array->key_exists($key) becomes array_key_exists($key, $array) > > (Is there even any other?) > > For phase 1 we could skip the functions which gets the first argument by > reference (walk, sort) and figure it out later. Hand waving yes but never > let perfect stand in the way of good enough :) > > Look how nicely this reads: > > $array->map($fn)->filter($fn2) > > Compared to array_filter(array_map($fn, $array), $fn2) > > I see no BC concerns here because in any previous PHP versions this is a > fatal error. I do not see any syntax ambiguity either but here I am > probably just naive. It could also be usable with user defined functions. > > What do you think? > > Karoly Negyesi >