Skip to content
Advertisement

Default value for reference argument in PHP function

Is there any reliable way to know if a function reference argument has been passed?

I’ve seen answers here in Stack Overflow that suggest to give it a default value and check that value, but I’ve tested it and it’s not 100% reliable because you can’t check if the argument hasn’t been set or if it has been set to a variable with the same value than the default one.

function fn (&$ref = null) {
    if ($ref === null)
        echo "ref null";
    else
        echo "ref not null";
}
$var = null;
fn($var); // ref null

function fn2 (&$ref = -1) {
    if ($ref === -1)
        echo "ref === -1";
    else
        echo "ref !== -1";
}
$var = -1;
fn2($var); // ref === -1

I’m running PHP 7.2

Advertisement

Answer

You can check the number of arguments passed into the function using func_num_args()

function fn (&$ref = null) {
    echo func_num_args().PHP_EOL;
    if ($ref === null)
        echo "ref null".PHP_EOL;
    else
        echo "ref not null".PHP_EOL;
}
$var = null;
fn($var);
fn();

will give

1
ref null
0
ref null
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement