[英]PHP validation booleans using filter_var
I'm using filter_var
to validate boolean values but I did not expect it to not recognize FALSE
. 我正在使用
filter_var
来验证布尔值,但我没想到它不能识别FALSE
。 Why does this happen? 为什么会这样?
filter_var(FALSE, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
returns 回报
null
filter_var
is new as of PHP 5.2. filter_var
是PHP 5.2的新版本。 You've run into a known bug: https://bugs.php.net/bug.php?id=49510 Feel free to vote on or comment on that bug. 您遇到了一个已知的错误: https : //bugs.php.net/bug.php? id = 49510随意投票或评论该错误。
You're trying to do something like this: 你正试图做这样的事情:
$v = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
There are a number of cheap workarounds like this: 有许多廉价的解决方法,如下所示:
$v = $v===FALSE ? FALSE : filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
It sounds like this is actually how it's supposed to work, strangely enough (yes, my mind was blown by that). 听起来这实际上是它应该如何工作,奇怪的是(是的,我的思绪被吹得那么)。 From https://bugs.php.net/bug.php?id=51344
来自https://bugs.php.net/bug.php?id=51344
This is going to sound insane when you've looked at the underlying filter code, but this is actually correct according to the documentation: the default behaviour of filter_input() is to return NULL for non-existent inputs and false when validation fails, and FILTER_NULL_ON_FAILURE simply flips that behaviour to false for non-existent inputs and NULL on validation failure.
当您查看底层过滤器代码时,这听起来很疯狂,但根据文档,这实际上是正确的:filter_input()的默认行为是为不存在的输入返回NULL,并在验证失败时返回false,并且对于不存在的输入,FILTER_NULL_ON_FAILURE简单地将该行为翻转为false,并在验证失败时将该行为翻转为NULL。 (No, I don't have a clue where that would be useful either, and the name of the flag is unfortunate in the filter_input() context, since it implies that NULL wouldn't normally be returned. It makes more sense when used with filter_var(), which doesn't have the non-existent input case.)
(不,我也不知道哪个也有用,并且在filter_input()上下文中标志的名称是不幸的,因为它暗示通常不会返回NULL。使用时更有意义使用filter_var(),它没有不存在的输入大小写。)
[table omitted due to SO formatting]
[由于SO格式化而省略了表格]
I'll pop a comment into the filter_input() and filter_input_array() implementations to note that this is by design, even though the code does kind of look wrong.
我将在filter_input()和filter_input_array()实现中弹出注释,注意这是设计的,即使代码看起来有点错误。
Closing Won't Fix.
关闭不会修复。
This was the behaviour when filter_var
was first introduced with version 5.2 and resolved at some point after 5.4 as is seen by this https://3v4l.org/Cv1MZ 这是
filter_var
最初在5.2版本中引入并在5.4之后的某个时刻解决的行为,如此https://3v4l.org/Cv1MZ所示
Starting from version 5.4 this is what happens: 从版本5.4开始,这是发生的事情:
var_dump(filter_var(FALSE, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
bool(false)
布尔(假)
which makes much more sense. 这更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.