Named Arguments in PHP 8.0

Named Arguments in PHP 8.0

PHP supports positional arguments. It means that we need to pass these arguments to a function or method based on the parameter position. The order of these arguments are important, so we need to pass the values to the correct parameter.

<?php

$str = substr('Hello world!', 6, 5);

Since PHP 8.0, we can use named arguments. It means that we can pass these arguments to a function or method based on the parameter name. Named arguments are self-documenting and makes code more readable.

<?php

$str = substr(string: 'Hello world!', offset: 6, length: 5);

The order of the named arguments are not important. In the following code, we pass arguments in the different order than they are defined in the function declaration:

<?php

$str = substr(string: 'Hello world!', length: 5, offset: 6);

We can pass named arguments with positional arguments. In this case, the positional arguments must always come first. If we pass a positional argument after a named argument, then PHP throws a fatal error.

<?php

$str = substr('Hello world!', offset: 6, length: 5);

Named arguments are very useful when a function has default parameters. In the following code, we have to specify the default value for pad_string parameter if we want to change the value of pad_type parameter:

<?php

$str = str_pad('Hello', 9, ' ', STR_PAD_BOTH);

Named arguments allows skipping default values. In the following code, we skipped the default value for pad_string parameter in order to change the value for pad_type parameter:

<?php

$str = str_pad('Hello', 9, pad_type: STR_PAD_BOTH);

Leave a Comment

Cancel reply

Your email address will not be published.