phpfunctionfunction-signature

Pass default value instead of reference


I have a function like this (using PHP 7.1):

function myfunction(&$first = null, $second = null)
{   // do something
}

What I want to achieve is to pass null as the first parameter and pass something as the second parameter:

myfunction(null, $something);

When I do that I get the "Only variables can be passed by reference" error.

But of course, null is the default of the first parameter, so the function was designed to handle null as the first parameter.

Is there a way to do it?


Solution

  • Instead of sending null, you can send an undeclared variable, like (DEMO):

    <?php
    function myfunction(&$first = null, $second = null)
    {   // do something
    }
    myfunction($null, $something);
    

    This will serve the purpose of executing the function and not breaking your code.

    PHP 8+:

    In PHP 8 we have Named Parameters, so we don't even need to pass the $first param if we don't want to (DEMO):

    <?php
    function myfunction(&$first = null, $second = null)
    {   // do something
    }
    myfunction(second: $something);