/    Sign up×
Community /Pin to ProfileBookmark

Collection of Items and foreach loop

I’ve got an object, let’s just say it’s a Person object with usual properties Name, Age Height etc

I’ve also got a PersonCollection class with a private property items which is type array.

When PersonCollection is constructed it gets all my people from a database and creates person objects adds them to an array.

What I want to do is loop through my PersonCollection class and print each name

“`
foreach ($PersonCollection as $Person){
echo $Person->getName();
}
“`

Now, I have the method getName within my person Class.

When I var_dump person collection, I get this

>

object(PersonCollection)[133]
> public array ‘items’ =>
> array (size=5)
> 0 =>
> object(Person)[262]
> private int ‘id’ => int 1
> private string ‘PersonName’ => string ‘Steve’ (length=7)
>
> array (size=4)
>
> private ‘servername’ (dbh) => null
> private ‘username’ (dbh) => null
> private ‘password’ (dbh) => null
> private ‘dbname’ (dbh) => null
> private ‘charset’ (dbh) => null
> 1 =>
> object(Person)[266]
> private int ‘campaignId’ => int 2
> private string ‘PersonName’ => string ‘James’ (length=9)
> ….

This is my error, I suspect $Person is an array not an object?

>

Fatal error: Uncaught Error: Call to a member function getName() on array in C:

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@kiwisauthorNov 11.2020 — Troubleshooting, when I do this inside my foreach

echo $person[1]->getName()

I get the first record only, when I make it 2 I get the second. So What's PersonCollection if it's not my root array level
Copy linkTweet thisAlerts:
@kiwisauthorNov 11.2020 — Solved, I need to return just the array property. So

foreach ($PersonCollection->getItems() as $Person){
Copy linkTweet thisAlerts:
@NogDogNov 11.2020 — For extra credit, you can look into having the collection class implement the [u][Iterator interface](https://www.php.net/manual/en/class.iterator.php)[/u]. Whether it's worth the bit of extra up-front work so that you can just do foreach($personCollection as $person) I'll leave up to you. :)
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...