PHP中TRUE和FALSE常量定义之间的不一致

Agn*_*kas 2 php casting

因此,有时我会把头撞到墙上。

var_dump(ord(true), ord(false));
Run Code Online (Sandbox Code Playgroud)

给出:

int(49)
int(0)

因此,将TRUE转换为ASCII代码49-数字1,将FALSE转换为ASCII代码0(零字节)。为什么在将TRUE / FALSE转换为字符串时出现这种不一致?为什么不能将FALSE转换为ASCII码48-期望整数上下文的数字0(因为TRUE为'1')?

这种定义的最大问题是,如果将布尔值存储在某些变量中,然后将其保存在数据库中,则TRUE将存储为'1',而FALSE将存储为''-空字符串。因此,在存储到数据库之前,您需要转换为integer (int)($bool_variable)。鉴于PHP支持全自动类型转换,因此在某些情况下执行手动强制转换的需求非常令人沮丧,而且有点愚蠢(要么所有类型都可以互换,要么用户必须在所有类型之间自行执行强制转换)。

有任何想法吗?

dec*_*eze 5

It inherently doesn't make sense to ask for the ord of a bool. ord expects a string, so casts any input to a string. true casts to '1', and false casts to ''. The ord of '1' is 49, and the ord of an empty string is 0.

That doesn't mean that true and false are defined as such. true is defined as true and false is defined as false. It's merely the type casting rules that you're stumbling over (and yes, they're arguably arcane). Most databases support native boolean types, or their PHP database API will convert PHP booleans to the database's equivalent, as long as you use the API correctly.

As for why those casting rules exist:

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

https://www.php.net/manual/en/language.types.string.php#language.types.string.casting

不,没有什么比这更有意义了。

  • @AgniusVasiliauskas“为什么”对于具有25年历史的编程语言始终是一个棘手的问题。我们也许可以提出有用的方案。我们也许可以指出从中选择的其他语言;但是我们可能不得不说“就是这样”。不管哪种方式,它都与ord()或'\ 0'无关,或者如果它为'0'则您的特定数据库代码会更简单。 (2认同)
  • @deceze我认为这*有点*不公平。有些事情只是错误,但是许多错误是从其他语言借来的,例如Perl甚至C。在这种情况下,Perl确实具有相同的行为(尝试`perl -e'print 1 == 1;'和`perl -e'print 1 == 2;'`); 哪个当然会引出问题-您总是可以问“为什么”,但很少会得到很好的答案。 (2认同)