Laravel 检查属性存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46301623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel check property exist
提问by Igor Ostapiuk
How I can check existing property $this->team->playerAssignment->player
in more rational way? Now I check it like this:
我如何$this->team->playerAssignment->player
以更合理的方式检查现有财产?现在我像这样检查它:
if ($this->team)
if (($this->team->playerAssignment))
if (($this->team->playerAssignment->player))
回答by Nurlan Nuriyev
Try isset php function.
试试isset php函数。
isset — Determine if a variable is set and is not NULL
isset — 确定变量是否已设置且不为 NULL
if(isset($this->team->playerAssignment->player)){
}
回答by Meloman
The best way is
最好的办法是
if (
isset($this->team)
&& isset($this->team->playerAssignment)
&& isset($this->team->playerAssignment->player)
){
// your code here...
}
Because PHP will stops if the first is to false
, if first object exists, it continue to second, and third condition...
Why not use only && $this->team->playerAssignment->player
?! because if player has 0
for value it will be understood as a false
but variable exists !
因为如果第一个是false
,PHP 会停止,如果第一个对象存在,它会继续第二个,第三个条件......为什么不只使用&& $this->team->playerAssignment->player
?!因为如果玩家0
有价值,它将被理解为一个false
但变量存在!