【问题标题】:PHP - Trying to get property of non-objectPHP - 试图获取非对象的属性
【发布时间】:2012-07-22 03:09:57
【问题描述】:

我正在尝试遍历一个名为 items 的对象属性,其中包含一个数组:

foreach ($this->footerList->items as $item)

当我执行该语句时,我收到一条错误消息 - “尝试获取非对象的属性”,即使

var_dump($this->footerList) 

表明$this->footerList 确实包含items 数组。

object(FooterModel)#13 (1) 
{ 
    ["items"]=> array(3) 
    { 
        [0]=> array(5) 
        { 
             ["id"]=> string(20) "terms-and-conditions" 
             ["title"]=> string(20) "Terms and Conditions" 
             ["url"]=> string(23) "home/termsandconditions" 
             ["label"]=> string(20) "Terms and Conditions" 
             ["authenticatedOnly"]=> string(5) "false" 
        } 
        [1]=> array(5) 
        { 
             ["id"]=> string(14) "privacy-policy" 
             ["title"]=> string(14) "Privacy Policy" 
             ["url"]=> string(18) "home/privacypolicy" 
             ["label"]=> string(14) "Privacy Policy" 
             ["authenticatedOnly"]=> string(5) "false" 
         } 
    } 
} 

谁能帮我弄清楚为什么循环语句不能解析$this->footerList->items

【问题讨论】:

  • 请显示更多代码,var_dump($this->footerList->items); 说什么?
  • 确保您在 foreach 循环的同一范围内调用了 var_dump

标签: php arrays object


【解决方案1】:

应该是

foreach ($this->footerList["items"] as $item)

【讨论】:

  • 如果$this->footerListobject(FooterModel) 为什么需要这样做?
  • $this->footerList 是一个数组,而不是一个对象——因此是“非对象”。
  • 如果$this->footerList 是一个数组,那么var_dump($this->footerList) 将回显array(1){...} 而不是object(FooterModel)
  • 它是一个以items 数组作为属性的对象,simple example 将向您展示。
【解决方案2】:

当您尝试使用 $this 而不是在类内部,您尝试将数组作为对象或静态方法引用时,最常见这种情况。

您需要提供更多代码才能获得更清晰的答案。

更新

我格式化了你的输出。

foreach ( (object) $this->footerList->items as $item)

以上内容会将您的所有子数组转换为对象,以便您按照计划的方式使用代码。

【讨论】:

    猜你喜欢
    • 2017-08-21
    • 2011-08-02
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多