php 判断 if (empty($user->published_at) != empty($user_input['published_at'])) 这个很简洁

这里的逻辑是:

  • 如果 $user->published_at 为空,并且 $user_input['published_at'] 不为空,或者
  • 如果 $user->published_at 不为空,并且 $user_input['published_at'] 为空,

那么条件将成立。这种检查通常用于确定某个值是否发生了变化,特别是从无到有或从有到无的情况。

假设您的意图是检测 published_at 字段从空到非空,或从非空到空的变化。如果这符合您的业务逻辑需求,那么这段代码是有效的。但务必确认,这种比较确实符合您的应用场景,尤其是在处理可能为 0'0' 等特殊值时,因为 empty() 会将它们视为空。

还有其他方法可以做到:

方法一:直观

if ((!empty($user->published_at) && empty($user_input['published_at'])) || (empty($user->published_at) && !empty($user_input['published_at']))) {
// 执行操作
}

方法二:三元运算符

if ((bool)$user->published_at != (bool)$user_input['published_at']) {
// 执行操作
}

方法三:封装函数(频繁使用时)

function hasStateChanged($original, $new) {
return (bool)$original != (bool)$new;
}

if (hasStateChanged($user->published_at, $user_input['published_at'])) {
// 执行操作
}

方法四:简化逻辑(使用XOR运算符(异或))

if (!empty($user->published_at) xor !empty($user_input['published_at'])) {
// 执行操作
}

虽然 xor 在特定情况下很有用,但在实际编程中使用较少,部分原因是它的优先级较低,可能会导致意外的结果,尤其是在复杂的逻辑表达式中。

// 可能导致意外结果
if ($a xor $b && $c) {
// 不清楚逻辑意图,因为 && 的优先级高于 xor
}

正确的做法应该是:

if (($a xor $b) && $c) {
// 现在清楚地表示了先进行 xor 运算,然后与 $c 进行逻辑与
}

posted @ 2024-05-16 16:38  阿拉灯参丁  阅读(2)  评论(0编辑  收藏  举报