PHP Page 4 - Coding Examples of the Iterator, Countable and ArrayAccess SPL Interfaces in PHP 5 |
As I said in the section that you just read, I’m going to finish this tutorial by coding an example that demonstrates how to use the “count(),” “offsetExists()” and “offsetGet()” methods implemented by the “MySQLi_ResultWrapper” class. These will allow you to count rows in a given result set, as well as access specified elements in it. The code sample that performs all of these tasks is as follows: <?php
try { // connect to MySQL $db = MySQLiWrapper::getInstance(array('host', 'user', 'password', 'database'));
// perform query $result = $db->runQuery('SELECT * FROM users');
// count the number of rows in result set echo 'Number of rows: ' . $result->count();
// check if given offset exists if ($result->offsetExists(1)) { echo 'Row exists!'; } else { echo 'Row does not exists!'; }
// get a row according to a given offset $user = $result->offsetGet(1); echo '<p>First Name: ' . $user->fname . ', Last Name : ' . $user->lname . '</p>'; }
// catch exceptions catch(Exception $e) { echo $e->getMessage(); exit(); } Once again, the earlier code fragment shows in a nutshell why implementing the Countable and ArrayAccess SPL interfaces is so convenient. In this particular case, the methods inherited from the interfaces are used to determine the number of rows contained in a data set, and to access a specific record by its offset. And with this last example, I’m finishing this article that explores the Iterator, Countable and ArrayAccess interfaces packaged with the Standard PHP Library. Feel free to edit all of the code fragments shown in this article. Doing this will surely give you more ideas for how to implement these interfaces in a few other creative ways. Final thoughts Sad but true, we’ve come to the end of this series. Hopefully, the code samples shown in its six parts will give you a good idea of how to implement the Iterator, Countable and ArrayAccess SPL interfaces within different classes. As you saw for yourself, in this particular case the interfaces were implemented by a class that processes MySQL result sets, but naturally they can be used for constructing classes that will handle different data collections, such as XML nodes and flat text files rows. The possibilities and endless. See you in the next PHP tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|