PHP - Trying to get property of non-object

2020-03-26 00:11发布

问题:

I'm trying to iterate through an object property called items that contains an array:

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

When I execute the statement, I get an error saying - "Trying to get property of non-object" even though

var_dump($this->footerList) 

shows that $this->footerList does indeed contain an items array.

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" 
         } 
    } 
} 

Can someone please help me figure out why the loop statement can't resolve the $this->footerList->items?

回答1:

It should be

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


回答2:

This is most commonly seen when you are trying to use $this and not inside of a class, your are trying to reference an array as an object or within a static method.

You will need to provide some more code to get a clearer answer.

Update

I formatted your output.

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

The above will cast all your subarrays to objects to allow you to use your code the way your planned it.