The PHP named arguments are the names of the arguments through passing the values, which allow you to add a name for the argument beside the value and that can be separated with the double dots.
Let’s see an example.
<?php
function that_is_func( $val1, $val2 ) {
echo $val1 . " this is " . $val2;
}
rename_it(
val2 : "val 2",
val1: "thanks ,"
);
?>
So, you don’t need to fill the function arguments by order. Anyway, this feature is appeared in PHP8. Before that, we were using the function arguments by order.
Passing PHP Named Arguments with Positional Arguments
PHP8 allows you to create a mix between the position arguments and named arguments. For example.
<?php
function get_user( $username, $age, $job ) {
return array(
"name" => $username,
"age" => $age,
"job" => $job
);
}
get_user(
"Montasser",
age: "34 years old",
job: "Web Developer"
);
?>
This will return the array correctly according to the passed arguments.
Wrong Position with PHP Named Arguments
When set name for a specific parameter and then changing the position of other arguments without names, that will occur an error, let’s see an example.
<?php
function concate_strings( $string, $value, $delimiter ) {
return $string . $delimiter . $value;
}
?>
In this example, I will change the position of the arguments after adding a name for only the last parameter.
<?php
concate_strings(
delimiter: ',',
"string 1",
"value 2"
);
?>
It will show you the following error.
Fatal error: Cannot use positional argument after named argument in /tmp/728b7ctla5vnj5r/tester.php on line 9
So the correct calling would be like the below.
<?php
concate_strings(
"string 1",
"value 2",
delimiter: ','
);
?>
Wrapping Up
The named arguments are a new feature of PHP8, it allows you to name the argument when you pass it as a value within the calling function.
You will not able to define a positional argument after named argument.