Re: [PHP-DEV] [VOTE] Named arguments

This is only part of a thread. view whole thread
July 10, 2020 12:56 (Rowan Tommins)
On Fri, 10 Jul 2020 at 11:24, Marco Pivetta <> wrote:

> If "array" is all you have to pass on as input, `fromArray` is what you > can certainly use: that's useful when de-serializing from JSON input, DB, > serialized state, etc. > > It certainly isn't meant to pass in the array via hand-crafted map: that's > what other (additional) named ctors would be for. >
As I said in my previous response, I think this comes down to an unfortunate example - if what you actually have is an array, then yes, fromArray makes sense. One of the use cases for named parameters happens to look superficially similar to that, because it can be worked around by first creating an array, and then passing it somewhere. But the input you actually have is not an array, it is a set of variables from multiple sources, or a set of hard-coded parameters of different types that configure the functionality. One aspect I'd like to highlight is that named parameters aren't just useful for large numbers of individual parameters, but large numbers of _valid combinations_. For instance, with two optional parameters, you can quite easily have named methods to omit one or the other: function fromFoo($foo) function fromBar($bar) function fromFooAndBar($foo, $bar) You could even skip the third method by having optional parameters on one or both of the other two. But this list would increase exponentially; with only three parameters, you would need: function fromFoo($foo) function fromBar($bar) function fromBaz($baz) function fromFooAndBar($foo, $bar) function fromFooAndBaz($foo, $baz) function fromBarAndBaz($bar, $baz) function fromFooAndBarAndBaz($foo, $bar, $baz) Right now, there is no elegant way to combine these into one function signature. Named parameters are one solution, because they let you specify defaults for all parameters: function fromFooAndOrBarAndOrBaz($foo=42, $bar=true, $baz=[]) Another solution is parameter skipping, which was declined largely because people preferred named params: The only other alternative I know of is the builder pattern ($builder->withFoo($foo)->withBar($bar)->withBaz($baz)->build()), which at least makes the boilerplate scale linearly rather than exponentially, but is still going to require dozens of lines of code to achieve what named parameters can do with one. Regards, -- Rowan Tommins [IMSoP]