If you're like me, then I'm certain that you'll want to see an example that illustrates how the previous MySQL driver works. With that idea in mind, below I coded a basic script that runs two queries against a fictional "users" MySQL table. As expected, the connection to the database server is made only once: <?php
try { // connect to MySQL $db = MySQLiWrapper::getInstance(array('host', 'user', 'password', 'database'));
// fetch users from database $users = $db->runQuery('SELECT * FROM users');
// display user data foreach ($users as $user) { echo 'First Name: ' . $user->fname . ' Last Name: ' . $user->lname . '<br />'; }
// fetch users' first names from database $users = $db->runQuery('SELECT fname FROM users');
// display user data foreach ($users as $user) { echo 'First Name: ' . $user->fname . '<br />'; }
} // catch exceptions catch(Exception $e) { echo $e->getMessage(); exit(); } As the above script shows, it's now possible to run multiple queries against a selected database table without having to spawn multiple connections to MySQL, by using a simple static variable created inside a single method. From this point on, feel free to edit and improve the definitions of the classes shown in this tutorial. This process will surely give you more ideas for how to use static properties in new and creative ways. Final thoughts It's hard to believe, but we've come to the end of the series. Hopefully, this short exploration of the use of static properties within PHP 5 classes has been helpful to you, as in the course of the series you learned how to employ them within a class that can be used as a simple, yet functional MySQL abstraction layer. Ranging from implementing the Singleton and Lazy Loading design patterns, to improving the individual behavior of methods, static variables can be really handy. However, as with many other features offered by PHP 5, they should be used with caution and consciously. See you in the next PHP tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|