Source: stitcher.io

PHP 8: named arguments

Category: PHP, api

If you enjoy reading my blog, you could consider supporting me on Patreon. You might have guessed it from the examples: named arguments allow to pass input data into a function, based on their argument name instead of the argument order.

Take our DTO example from before: You could construct it like so: However, having an ordered argument after a named one would throw an error: Next, it's possible to use array spreading in combination with named arguments: If, however, there are missing required entries in the array, or if there's a key that's not listed as a named argument, an error will be thrown: It is possible to combine named and ordered arguments in an input array, but only if the ordered arguments follow the same rule as before: they must come first!

Take this example: PHP will silently allow changing the name of $event to $myEvent, and $handler to $myHandler; but if you decide to use named arguments using the parent's name, it will result in a runtime error: Runtime error in case $listener is an instance of MyListener

That's most there is to tell about named arguments, if you want to know a little more backstory behind some design decisions, I'd encourage you to read the RFC.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners