将未设置的变量传递给函数
我的代码:
function Check($Variable, $DefaultValue) {
if(isset($Variable) && $Variable != "" && $Variable != NULL) {
return $Variable;
}
else {
return $DefaultValue;
}
}
$a = Check(@$foo, false);
$b = Check(@$bar, "Hello");
//$a now equals false because $foo was not set.
//$b now equals "Hello" because $bar was not set.
- 当变量不存在并传递给函数(抑制错误)时,实际传递了什么?
- 该函数是否存在任何未定义的行为?
- 是否有更好的方法来包装变量存在的测试并从函数提供默认值?
- 测试变量时
isset()
在底层检查什么?
编辑:
默认值由用户定义。有时它是一个数字,有时是一个字符串。
My code:
function Check($Variable, $DefaultValue) {
if(isset($Variable) && $Variable != "" && $Variable != NULL) {
return $Variable;
}
else {
return $DefaultValue;
}
}
$a = Check(@$foo, false);
$b = Check(@$bar, "Hello");
//$a now equals false because $foo was not set.
//$b now equals "Hello" because $bar was not set.
- When a variable doesn't exist and is passed to the function (suppressing the error) what is actually passed?
- Is there any undefined behaviour that this function could exhibit?
- Is there a better way of wrapping the testing for variable existence and supplying a default value from a function?
- What does
isset()
check under the hood when testing a variable?
EDIT:
The default value is there to be user defined. Sometimes it will be a number, sometimes a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过放置 & 将变量通过引用传递给方法。声明函数时放在它前面。然后,您只需检查它是否在函数内部设置,而不必担心在传递未设置的值时抑制警告。
You can pass the variable to the method by reference by putting an & in front of it when declaring the function. Then you can just check if it set inside the function and not have to worry about suppressing warnings when passing the value that isn't set.
null
将被传递empty($var)
完成的,例如:Check(empty($foo) ? null : $foo)
,尽管根据具体情况isset
可能更合适isset
所做的正是 记录 -- 它测试范围内是否存在这样的变量并且其值与null
不同null
will be passedempty($var)
, e.g.:Check(empty($foo) ? null : $foo)
, although depending on the circumstancesisset
may be more appropriateisset
does is exactly documented -- it tests if there is such a variable in scope and its value is not identical tonull
在这种情况下,您尝试读取不存在的变量
因此,您得到
null
——它被传递给函数。我不这么认为——除了使用
@
运算符并不是一个很好的做法。In this case, you try to read from a non-existent variable
So, you get
null
-- which is passed to the function.Not that I see -- except using the
@
operator is not quite a good practice.