user975343
user975343

Reputation:

Class field as array of objects

i've declared the next class:

class Background{ 
    protected $users = array() ;
 ......
 }

and I employ $users as array of User() , which is another object i've created. The problem comes up when I try to use this method :

function createB(){
        foreach($this->users as $user){
            $name = $user->getName();
        }
    }

And $user->getName() is actually an error becuase $user is not seen as an object. What might be the reason for this ?

Thanks in advance

Upvotes: 0

Views: 418

Answers (1)

Kasia Gogolek
Kasia Gogolek

Reputation: 3414

The problem might be with the $users not actually getting populated Try adding this to prevent this sort of issue. if this doesn't help, please add information as to how $users is populated.

function createB()
{
    if(!empty($this->users))
    {
        foreach($this->users as $user)
        {
            if($user instanceof User)
            {
                $name = $user->getName();
            }
        }
    }
}

Upvotes: 1

Related Questions