Quantcast

Creating Object Iterators in PHP

Items can be iterated with the help of arrays in PHP but when arrays are not available, there is alternate and even more efficient method to undertake the same task. This is particularly useful while reading records from a database or lines of text read from a file. In this tutorial, we would create a class that counts the number of users who are logged in to a web application by retrieving records from a database. First, we need to define a class to store ID and email.

For this, we also need a LoggedIn class which would handle a collection of users who have logged in.

The constructor of this class would call the function FetchLoggedIn() to run the database query:

In the above piece of code, $this->cursor is the current record number (zero based). It’s initially set to -1 because we haven’t retrieved any records. $this->item will hold the current User object. $this->rec is the set of records (if any) returned from our SQL query. $this->rec->setFetchMode line sets the default PDO fetch mode. When we fetch a row, a new instance of the User class is returned with the $id and $email properties mapped to the record.

Since our class implements Countable, we must create a public method named count () which returns the number items in the collection — in this case, the number of rows returned by our SQL query:

The following line calls next (), our second Iterator method:

This code can be used to can count or iterate over logged-in users and is a pretty efficient alternative to arrays.

Looking for a quality hosting service? here are a few I suggest.
BlueHost | HostGator | Media Temple
Admin
Admin
Ali has been an entrepreneur in web, video and related technologies. Having worked with many business across the globe, Ali stands truly a great pillar in the business working with him.