php - 使用 null 合并运算符时如何键入 cast?
问题描述
说我有这个:
$username = (string) $inputs['username'] ?? null;
如果$inputs['username']
设置了,那么我希望它转换为string
. 如果没有设置,那么$username
应该是null
.
但是,此时如果$inputs['username']
未设置,它将是一个空字符串而不是 null。
我怎样才能解决这个问题?还是这是故意的行为?
解决方案
如果您要在非空情况下返回的值与您正在测试的值相同,则只能使用空合并运算符。但在你的情况下,你想在返回时施放它。
因此需要使用常规条件运算符并显式测试值。
$username = isset($input['username']) ? (string) $input['username'] : null;
推荐阅读
- sql - 编写查询检索第一个值而没有顶部,获取,限制
- r - 用乳胶在绘图中标记轴
- php - 多个条件 findFirst
- sql-server - Django:无法连接到 Microsoft SQL Server
- video-streaming - 从本地文件上传视频时不允许加载本地资源错误
- nodemcu - 是否可以将 NodeMCU 连接到 3G 网络,如果可以,如何连接?
- regex - Visual Studio 查找和替换字符串两端的字符
- python - Odoo 可以跟踪计算领域的变化
- ios - Alamofire - 带有自定义标头的 Rest API 调用
- azure - 请参阅 ARM 模板中的 VSTS 构建/发布变量