0

Suppose I have

function test($a, $b, $c=3, $d=4) {
  // ...
}
test(1, 2);          // $c == 3, $d == 4
test(1, 2,     , 9); // syntax error
test(1, 2, null, 9); // $c == null

I want to be able to set $d as 9, but leaving the default value of $c at 3.
Sure, if I know the default value, I can set it. But it's a bad solution because firstly I must know it, and secondly if it gets changed in the function declaration, I have to change it in my code too.
Another solution would be to swap the parameters order, but the code I have to deal with is fairly more complicated and so I would like to know if there is a "standard" solution in PHP, to pass a parameter letting the interpreter use the default value if present.

1
  • 2
    PHP8 introduced named arguments Commented May 19, 2022 at 9:54

2 Answers 2

1

In php 8.0.0 you can specify the arguments.

<?php
function test($a, $b, $c=3, $d=4) {
  var_dump( $c );//int(3)
}

test(1, 2, d:9); // $c == 3
?>

Named Arguments

Sign up to request clarification or add additional context in comments.

Comments

0

As per my knowledge We need to make logic for this as

function test($a, $b, $c=null, $d=null) {
    if (null === $c) { $c = 3; }
    if (null === $d) { $d = 4; }
    echo $a." ".$b." ".$c." ".$d;
}
test('',1,null,5);

Output: 1 3 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.