php - 使用返回 true 或 false 的函数的 PHP 最佳实践是什么?

标签 php function boolean typing

玩过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 值 TRUEFALSE .典型案例是以 is 为前缀的函数, 比如 isValidInput .人们通常期望这样的函数返回 TRUEFALSE .

另一方面,在某些情况下让您的函数返回“虚假”或“真实”值很有用。取 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/

相关文章:

php - 在 php/mysql 中对搜索实现拼写错误更正的最佳方法是什么?

PHP PDO bindParam() 和 MySQL BIT

php - 显示过去 3 年中每 3 个月按标记支付的付款

php - MySQL - 计算日期范围内的行出现次数,但将 null 转换为 0 以便显示

c - C 函数调用的返回值?

python - Python 类中的数学方法

c++ - 如果 (aCHAR == 'character' || 'another character' ) 问题

r - 将 R Shiny 应用程序保存为函数,并将参数传递给 Shiny 的应用程序

python - 双等于vs在python中

ios - 关于 BOOL 方法信息的小请求