说我有这个:
$username = (string) $inputs['username'] ?? null;
如
$inputs['username']
设置然后我希望它转换到 string
.如果是 不是 然后设置 $username
应该是 null
.但是,目前如果
$inputs['username']
未设置它将是一个空字符串而不是 null。我怎样才能解决这个问题?或者这是故意的行为?
最佳答案
如果要在非 null 情况下返回的值与要测试的值相同,则只能使用 null-coalesce 运算符。但是在您的情况下,您想在返回时转换它。
因此需要使用常规条件运算符并显式测试该值。
$username = isset($input['username']) ? (string) $input['username'] : null;
关于php - 使用空合并运算符时如何进行类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338510/