php默认参数 [英] php default arguments
问题描述
在PHP中,如果我有一个这样写的函数
In PHP, if I have a function written like this
function example($argument1, $argument2="", $argument3="")
我可以像这样在其他地方调用这个函数
And I can call this function in other place like this
example($argument1)
但是如果我想给第三个参数一些价值,我应该这样做吗
But if I want to give some value to the thrid argument, Should I do this
example($argument1, "", "test");
或
example($argument1, NULL, "test");
我认为两者都可以,但更好的方法是什么?因为以后如果在main函数中修改了$argument2的值,如果我有"",那会不会有什么问题?或者 NULL 是最好的选择?
I think both will work but what is the better way? Because in future if the value for the $argument2 is changed in the main function and if I have "", then will there be any problem? Or NULL is the best option?
谢谢
推荐答案
您可以使用:
example($argument1, '', 'test');
或
example($argument1, NULL, 'test');
您始终可以使用空字符串代替空字符串来检查 NULL:
You can always check for NULL using instead of empty string:
if ($argument === NULL) {
//
}
我认为这完全取决于带有 args 的函数内部发生了什么.
I think it all depends on what happens inside the function with the args.
这篇关于php默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!