Home > Mobile >  Skipping / not setting parameters in PHP functions with default values
Skipping / not setting parameters in PHP functions with default values

Time:05-19

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related