如果没有传递参数,我想要一个函数来发出错误信号。现在它会发出警告但会执行代码。
我调查了这个PHP Error handling missing arguments但我认为更多的是将输入转换为 null 或零的“空”问题。
我正在使用:
PHP 5.6.25 (cli) (built: Sep 6 2016 16:37:16)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
我有:
function go($x){
if(is_null($x))
print("|nil|"."\n");
else
print($x."\n");
}
并得到预期的结果
go(33);
> 33
go("Hello world");
> "Hello World"
go(null);
> |nil|
$in = null;
go($in);
> |nil|
$in = 44;
go($in);
> 44
但是如果我在没有参数的情况下调用它,我会得到
go();
> Warning: Missing argument 1 for go(), called in ...
> |nil|
在这个例子中我打印了|nil|但从更大的角度来看,它应该返回错误(或 null)以处理其他地方。
我研究过类似的东西
function go($x){
if(!isset($x)) die("muerto");
if(is_null($x))
print("|nil|"."\n");
else
print($x."\n");
}
但它会杀死(死亡?:-))空的和 null 的情况。
go();
> Warning: Missing argument 1 for go(), called in ...
> muerto
go(null);
> muerto
像往常一样,这是一个来自更详细代码的过度简化的示例。
非常感谢您的意见。
最佳答案
您可以使用默认值和func_num_args()
函数来处理没有传递参数的情况。例如:
function go($x = null){
if(func_num_args() === 0)
print("error: no argument passed"."\n");
else if(is_null($x))
print("|nil|"."\n");
else
print($x."\n");
}
关于PHP 处理函数中缺少的参数和空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429944/