首页 > 解决方案 > 使用 null 合并运算符时如何键入 cast?

问题描述

说我有这个:

$username = (string) $inputs['username'] ?? null;

如果$inputs['username']设置了,那么我希望它转换为string. 如果没有设置,那么$username应该是null.

但是,此时如果$inputs['username']未设置,它将是一个空字符串而不是 null。

我怎样才能解决这个问题?还是这是故意的行为?

标签: phpcastingphp-7null-coalescing-operator

解决方案


如果您要在非空情况下返回的值与您正在测试的值相同,则只能使用空合并运算符。但在你的情况下,你想在返回时施放它。

因此需要使用常规条件运算符并显式测试值。

$username = isset($input['username']) ? (string) $input['username'] : null;

推荐阅读