By given this function:
function doSomething($var1, $var2, $var3 = true, $var4 = false){
// function lines here...
}
I want to call the function and pass values to the arguments 1, 2 and 4 bypassing the third argument as it is optional. Is this possible in PHP?
Something like:
$var1 = 2;
$var2 = "some text";
$var4 = true;
$result = doSomething($var1, $var2, $var4);
Or in this case I need to pass a value for the third argument, too?
I try to pass to a PHP function only those optional arguments, where I have a value different than the default one defined in the function itself.
2
Answers
In php 8.x you can use named arguments
Reference: https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments
You can do the following:
1 – Using your logic, you can’t bypass the 3rd parameter, but you can just define it when you call the function.
Other alternative:
Robert C. Martin. states the following
I hope I was able to help! Thanks!