【问题标题】:Laravel error "Trying to get property of non-object" when inside an if() condition在 if() 条件内时,Laravel 错误“尝试获取非对象的属性”
【发布时间】:2014-11-10 20:45:26
【问题描述】:

很奇怪,我可以在 if 语句之前访问该属性,如果我将 if 条件更改为其他内容,我也可以在 if 语句中访问该属性。但是尝试访问 if 条件内的属性会引发错误:

$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
      dd($city->market->id);  // <-Accessible here

      if (!in_array($city->market->id, $market_ids)){ // Error: Trying to get property of non-object

         dd($city->market->id); // Accessible here
         $market_ids[] = $city->market->id;

      }
});

错误:试图获取非对象的属性

有人遇到过这种情况吗?

【问题讨论】:

  • 您运行哪个 PHP 版本?

标签: php laravel laravel-4


【解决方案1】:

我认为,您应该确保对于您的每个城市,您的关系都不会返回 null

$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{

       if ($city->market === null) {
         echo " null market for ".$city->name."<br />";
         continue;
       } 


      if (!in_array($city->market->id, $market_ids)){ 

         $market_ids[] = $city->market->id;

      }
});

当您使用dd 时,您检查了它的第一个记录,这并不意味着对于第 2 行或第 3 行或更晚的行有相应的市场对象。例如,您有 100 个城市,其中 99 个有市场,其中 1 个没有。您将收到您询问的错误,因为其中一个您没有市场,因此您无法询问市场 ID。

所以要明确这个错误与ifin_array无关,因为如果你使用:

$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
      echo $city->market->id; // not dd but simply echo
});

你可能也会遇到同样的错误。

【讨论】:

  • 谢谢马尔辛!这是确切的问题。我的一个城市没有市场。
【解决方案2】:

试图获取非对象的属性 表示源 $city-&gt;market 在某些情况下不是对象,或检查此编辑:

$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
      $id = $city->market->id;

      dd($id);

      if ( ! in_array($id, $market_ids) ){ 

         dd($id);
         $market_ids[] = $id;

      }
});

【讨论】:

  • 在 if 条件之外它是一个对象。例如,我举例说明的第一个 dd()。
  • 尝试在单独的 var $id 中获取 $city-&gt;market-&gt;id 然后使用它,然后检查会发生什么
猜你喜欢
  • 2019-05-06
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多