PHP 8.0: Named Parameters

TypeNew Feature

PHP 8.0 supports optionally calling functions and class methods by specifying the parameter name, instead of calling them with the order of parameters.

PHP, and many other programming languages, support positional parameters: The caller passes the parameters in the same order the function/method declares its parameters.

In PHP 8.0, Named Parameter support is added, which means it's now possible to call a function/method by setting the parameters by their name.

Positional Parameters

function str_contains(string $haystack, string needle): bool {}
str_contains('FooBar', 'Foo');

Named Parameters

function str_contains(string $haystack, string $needle): bool {}
str_contains(haystack: 'FooBar', needle: 'Foo');

With Named Parameters, the call-site names the parameter value, and passes it to the called function. With named parameters, the order of the parameters are not important, as long as all the required parameters are passed.

For example, both of these statements are correct and functionally identical:

str_contains(haystack: 'FooBar', needle: 'Foo');
str_contains(needle: 'Foo', haystack: 'FooBar');

Named parameter feature offers more readability when calling a function with parameters that do not require to have a particular order, or cannot be made more intuitive.

    name: "Awesome",
    value: 'Yes',
    path: "/",
    domain: "",
    secure: true,
    httponly: true

The name of the parameter in declaration, without the $ sign will be the parameter name.

Documentation In Progress
This page is incomplete. Please check back later.