skip to Main Content

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


  1. In php 8.x you can use named arguments

    function foo(int $var_a, int $var_b, string $var_c) { ... }
    
    foo(var_a: 10, var_c: 'ola mi amigo');
    

    Reference: https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments

    Login or Signup to reply.
  2. 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.

    $var1 = 2;
    $var2 = "some text";
    $var4 = true;
    $result = doSomething($var1, $var2, true, $var4);
    

    Other alternative:

    function doSomething($values)
    {
       $var1 = $values['var1'] ?? null;
       $var2 = $values['var2'] ?? null;
       $var3 = $values['var3'] ?? true;
       $var4 = $values['var4'] ?? false;
       // do something cool
    }
    
    $var1 = 2;
    $var2 = "some text";
    $var4 = true;
    $result = doSomething(['var1' => $var1, 'var2' => $var2, 'var4' => $var4]);
    

    Robert C. Martin. states the following

    A function shouldn’t have more than 3 arguments. Keep it as low as
    possible. When a function seems to need more than two or three
    arguments, it is likely that some of those arguments ought to be
    wrapped into a class of their own. Reducing the number of arguments by
    creating objects out of them may seem like cheating, but it’s not.

    I hope I was able to help! Thanks!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search