如何更合理地查询现有房产
$this->team->playerAssignment->player
?现在我这样检查:
if ($this->team)
if (($this->team->playerAssignment))
if (($this->team->playerAssignment->player))
尝试 isset php 函数。
isset — 确定变量是否已设置且不为 NULL
if(isset($this->team->playerAssignment->player)){
}
以下内容始终最适合我:
if(isset(Auth::user()->client->id)){
$clientId = Auth::user()->client->id;
}
else{
dump('Nothing there...');
}
最好的方法是
if (
isset($this->team)
&& isset($this->team->playerAssignment)
&& isset($this->team->playerAssignment->player)
){
// your code here...
}
因为如果第一个条件是
false
,PHP 将停止,如果第一个对象存在,它将继续第二个和第三个条件...
为什么不只使用&& $this->team->playerAssignment->player
?!因为如果玩家有 0
的值,它将被理解为 false
但变量存在!
您可以通过空合并运算符轻松检查
if ($this->team->playerAssignment->player ?? null)
php 8 2024 更新在这里:使用 ?-> 运算符你可以这样做 if( $variable?->prop1?->prop2?->prop3 ){ ...