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 positional argument after a named argument then PHP throws fatal error.

<?php

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

Named arguments are very useful when function has default parameters. In the following code we must 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 to skip default values. In the following code we skipped the default value for pad_string parameter in order to change value for pad_type parameter:

<?php

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

Leave a Comment

Your email address will not be published. Required fields are marked *