HomePHP Page 3 - Implementing the Countable SPL Interface
Counting rows in result sets with the Countable SPL interface - PHP
In this third part of a seven-part series on the Iterator, Countable and ArrayAccess SPL interfaces, I give the MySQLi_ResultWrapper class developed in the previous part the capability of counting the number of rows contained in a given result set. I'll do that by implementing the "count()” method declared by the Countable interface. Doing this will make it possible to use an instance of the class to traverse data sets and count records as if they were plain PHP arrays, which is quite appealing to client code that works with the class’s API.
In the section that you just read, I stated that the previous “MySQLi_ResultWrapper” class was going to implement the Countable SPL interface, right? Well, in keeping with this, it’s mandatory to make the class include a “count()” method. In this case, this method will be simply a getter for the “num_rows” property, and its definition will be as follows:
// count rows in result set (implementation required by 'count()' method in Countable interface)
public function count()
{
return $this->num_rows;
}
For obvious reasons, the implementation of the “count()” method is extremely simple; all that it does is return to client code the value of the corresponding “num_rows” property, which contains the number of rows contained in a given result set. With the inclusion of this new method, the “MySQLi_ResultWrapper” class now has the ability to count database rows as if they were plain array elements.
Since the logic that drives the previous “count()” method doesn’t bear any further discussion, it’s time to show the complete source code of the “MySQLi_ResultWrapper” class, this time including the implementation of the Countable interface.
This last process will conclude this third part of the series, so if you want to learn more about it, read the following section.