Skip to main content
Named parameters, introduced in PHP 8.0, allow developers to pass arguments to a function by specifying the target parameter’s name rather than relying on its positional order in the function signature. This mechanism decouples the argument list from the function declaration order and allows explicit assignment of values to specific parameters.

Syntax

The syntax utilizes the parameter name (omitting the $ prefix) followed by a colon : and the value being passed.

Core Mechanics and Rules

1. Order Independence Arguments can be passed in any arbitrary sequence, provided all required parameters are fulfilled by the time the function executes.
2. Skipping Optional Parameters Named parameters allow the caller to skip parameters that possess default values without needing to explicitly pass those defaults for preceding optional parameters.
3. Mixing Positional and Named Arguments Positional and named arguments can be combined within a single function call. However, positional arguments must strictly precede named arguments. Once a named argument is declared in the argument list, all subsequent arguments must also be named.
4. Overwriting Arguments Passing a value to the same parameter multiple times—either via multiple named arguments or a combination of positional and named arguments—results in a fatal error.
5. Unknown Parameters Passing a named argument that does not exist in the target function’s signature throws an Error exception.

Advanced Behaviors

Argument Unpacking with Associative Arrays The splat operator (...) can unpack associative arrays into named parameters. The array keys are evaluated as the parameter names.
Interaction with Variadic Functions When named arguments are passed to a variadic function (a function utilizing ...$args in its signature), the named arguments that do not match specific declared parameters are collected into the variadic array. The parameter names are preserved as the string keys of that array.
Inheritance and Contract Implications Because parameter names are evaluated at runtime, they form a strict part of the class API contract. If a child class overrides a method and alters the parameter names, calls utilizing the parent’s parameter names will result in a runtime error, violating the Liskov Substitution Principle.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More