Laravel 检查 属性 是否存在
Laravel check property exist
如何以更合理的方式检查现有的 属性 $this->team->playerAssignment->player
?现在我这样检查:
if ($this->team)
if (($this->team->playerAssignment))
if (($this->team->playerAssignment->player))
尝试设置 php 函数。
isset — 确定变量是否已设置且不为 NULL
if(isset($this->team->playerAssignment->player)){
}
最好的方法是
if (
isset($this->team)
&& isset($this->team->playerAssignment)
&& isset($this->team->playerAssignment->player)
){
// your code here...
}
因为PHP如果第一个到false
就会停止,如果第一个对象存在,它会继续到第二个,第三个条件...
为什么不只使用 && $this->team->playerAssignment->player
?!因为如果玩家有 0
作为价值,它将被理解为 false
但变量存在 !
以下一直最适合我:
if(isset(Auth::user()->client->id)){
$clientId = Auth::user()->client->id;
}
else{
dump('Nothing there...');
}
您可以通过空合并运算符轻松检查
if ($this->team->playerAssignment->player ?? null)
如何以更合理的方式检查现有的 属性 $this->team->playerAssignment->player
?现在我这样检查:
if ($this->team)
if (($this->team->playerAssignment))
if (($this->team->playerAssignment->player))
尝试设置 php 函数。
isset — 确定变量是否已设置且不为 NULL
if(isset($this->team->playerAssignment->player)){
}
最好的方法是
if (
isset($this->team)
&& isset($this->team->playerAssignment)
&& isset($this->team->playerAssignment->player)
){
// your code here...
}
因为PHP如果第一个到false
就会停止,如果第一个对象存在,它会继续到第二个,第三个条件...
为什么不只使用 && $this->team->playerAssignment->player
?!因为如果玩家有 0
作为价值,它将被理解为 false
但变量存在 !
以下一直最适合我:
if(isset(Auth::user()->client->id)){
$clientId = Auth::user()->client->id;
}
else{
dump('Nothing there...');
}
您可以通过空合并运算符轻松检查
if ($this->team->playerAssignment->player ?? null)