因此,有时我会把头撞到墙上。
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支持全自动类型转换,因此在某些情况下执行手动强制转换的需求非常令人沮丧,而且有点愚蠢(要么所有类型都可以互换,要么用户必须在所有类型之间自行执行强制转换)。
有任何想法吗?
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"
. BooleanFALSE
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
不,没有什么比这更有意义了。