關於 orm 中 find 不存在的寫法

举例取得用户

if ($user = User::find(1)) {
   // 用户存在
}

要如何写成 当不存在时执行 if 内
当然以下这种写法是可以,但我想用上面的写法,不知是否可行

$user = User::find(1)
if (is_null($user)) {
    // 用户不存在
}
JellyBool

我试了一下,应该是可以的。你也可以测试一下

openwrtmail

这样写不影响结果。在php中null转换成bool值就是0;
但是为了代码的可读性,建议加上is_null();的方法 @brucewu

brucewu

因为我想写的精简一些
想要
if ($user = User::find(1)) {
   // 用户不存在时,上面这一个if 要如何改
}

sodasix
if(! $user = User::find(2)){
    // coding
}

userId 不存在, $user = null, null + !取反 等于 true 执行括号内的…

brucewu

怪了,我原本也是这样写
if(! $user = User::find(2))
当时 ide 编辑器给我报错
现在却又正常…
没事了,感谢…

BigHeader
if(isEempty($user)) {

}