php - 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
解决方案
您可以使用检查传递给函数的参数数量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
推荐阅读
- javascript - 我可以在 PDF 中运行 WebAssembly 吗?
- javascript - 有没有办法在尝试修改它时覆盖 Object 以实例化一个属性?
- c++ - c++ 中浮点数的 a = -a 和 *= -1 有区别吗?
- excel - 用户窗体在初始化代码时不填充
- python - 我的 jupyter 笔记本是笔记本不工作
- django - Django - 密码字段上的“此字段是必需的”错误
- multithreading - 设置要在 Julia Pro 中手动使用的线程数
- regex - 正则表达式 RE2:提取字符串末尾括号内的文本,包括括号,如果有多个,则仅提取最后一组
- typescript - 零个或所有可选但类型化的参数
- r - 用于汇总贷款数量的 R 函数