首页 > 解决方案 > PHP:这句话是什么意思?if ($isCopy = null !== $id) { // 做点什么 }

问题描述

我的 php 文件中有以下遗留代码:

$id = $request->getParameter('id', null);
if ($isCopy = null !== $id) {
     // Do domething
}

我所理解的是,它正在从 URL 中获取参数“id”并检查它是否为 NULL。我想了解这个逻辑是如何工作的?if ($isCopy = null !== $id)

标签: phpsymfony

解决方案


这解释如下:

$id = $request->getParameter('id', null);
if ($isCopy = (null !== $id)) {
     // Do domething
}

$isCopy 从 null !== $id 比较接收布尔结果,然后 if 语句使用它的值。

不过,应该避免这种结构。改用这个:

$id = $request->getParameter('id', null);
if ($id !== null) {
     // Do domething
}

或者,如果您将评估带到另一个代码块,并且想要突出显示 null id 的含义:

$id = $request->getParameter('id', null);
$isCopy = $id !== null;
if ($isCopy) {
     // Do domething
}

推荐阅读