phpforeacharrayobjectarrayiterator

PHP ArrayObject / ArrayIterator : concept with example


I'm trying to understand the concept of the Object Array in PHP. Up to date I was simply using regular arrays to loop through the list of records and display them in say table.

I know that I could do this using Object, but I'm not quite sure how to do it.

I understand the concept of a single Object instance with all properties representing the fields with their associated values populated from the database, which can be called like:

$objUser->first_name;

Now what I would like to understand, and simply cannot find a simple answer to is how to deal with let's say list of users, which I would like to display on one page. I've seen that there are ArrayObject, ArrayIterator etc., but simply cannot understand how they work so if someone could try to explain it with a few examples of how the above can be accomplished that would be much appreciated.

What I'm looking for is an object containing the list of elements, which I can loop through like so (if at all this is possible):

foreach($objUsers as $objUser) {
    echo $objUser->first_name;
}

Thanks.


Solution

  • It is possible. Have your object implement the Iterator interface, and then you will be able to foreach over it natively. (Note, you need to correctly implement the methods to advance and rewind your array)

    More info: