After playing with PHP, I discovered that true is returned as 1 and false as null.
这不是真的(没有双关语意).与许多其他语言一样,PHP具有“truthy”和“falsy”值,与其他值相比,它们的行为类似于TRUE或FALSE.
这是因为PHP使用弱类型(与strong typing相比).它在比较时会自动转换不同类型的值,因此最终可以比较相同类型的两个值.当你回显TRUE;在PHP中,echo将始终输出一个字符串.但是你传递了一个布尔值,必须在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?
尽可能精确,返回实际的布尔值TRUE或FALSE.典型情况是以isValidInput为前缀的函数.人们通常希望这些函数返回TRUE或FALSE.
另一方面,在某些情况下让函数返回“虚假”或“真实”值很有用.以strpos为例.如果它在零位置找到子字符串,则返回0(int),但如果找不到该字符串,则返回FALSE(bool).所以:
$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"