首页 > 解决方案 > PHP函数中引用参数的默认值

问题描述

是否有任何可靠的方法可以知道是否已传递函数引用参数?

我在 Stack Overflow 中看到了建议给它一个默认值并检查该值的答案,但我已经对其进行了测试,它不是 100% 可靠的,因为你无法检查参数是否尚未设置或是否它已被设置为一个与默认值相同的变量。

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

我正在运行 PHP 7.2

标签: phpreference

解决方案


您可以使用检查传递给函数的参数数量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();

会给

1
ref null
0
ref null

推荐阅读