玩过PHP,发现true返回1,false返回null。
echo (5 == 5) // displays 1
echo (5 == 4) // displays nothing
编写返回 true 或 false 的函数时,使用它们的最佳做法是什么?
例如,
function IsValidInput($input) {
if ($input...) {
return true;
}
else {
return false;
}
}
这是使用函数的最佳方式吗?
if (IsValidInput($input)) {
...
}
你会如何编写相反的函数?
IsBadInput($input) {
return ! IsValidInput($input);
}
您什么时候会使用 ===
运算符?
最佳答案
After playing with PHP, I discovered that true is returned as 1 and false as null.
那不是真的(没有双关语意)。与许多其他语言一样,PHP 具有“真实”和“虚假”值,其行为类似于 TRUE
。或 FALSE
与其他值相比时。
之所以如此,是因为 PHP 使用弱类型(与 strong typing 相比)。它在比较不同类型的值时会自动转换它们,因此它最终可以比较两个相同类型的值。当你echo TRUE;
在 PHP 中,echo
总是会输出一个字符串。但是你给它传递了一个 boolean 值,必须在 echo
之前将其转换为字符串。可以完成它的工作。所以TRUE
自动转换为字符串 "1"
, 而 FALSE
转换为 ""
.
When would you use the === operator?
这种弱类型或松散类型是 PHP 使用两个相等运算符 ==
的原因和 ===
.您使用 ===
当您想确保要比较的两个值不仅“相等”(或等效),而且类型相同时。在实践中:
echo 1 == TRUE; // echoes "1", because the number 1 is a truthy value
echo 1 === TRUE; // echoes "", because 1 and TRUE are not the same type (integer and boolean)
When writing functions that return true or false, what are the best practices for using them?
尽可能精确,返回实际的 boolean 值 TRUE
或 FALSE
.典型案例是以 is
为前缀的函数, 比如 isValidInput
.人们通常期望这样的函数返回 TRUE
或 FALSE
.
另一方面,在某些情况下让您的函数返回“虚假”或“真实”值很有用。取 strpos
, 例如。如果它在位置零找到子字符串,则返回 0
(int),但如果未找到该字符串,则返回 FALSE
( boolean )。所以:
$text = "The book is on the table";
echo (strpos($text, "The") == FALSE) ? "Not found" : "Found"; // echoes "Not found"
echo (strpos($text, "The") === FALSE) ? "Not found" : "Found"; // echoes "Found"
关于php - 使用返回 true 或 false 的函数的 PHP 最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643080/