To demonstrate the actual functionality of the $_connected static property just added to the "MySQLiWrapper" class, below I wrote a script that runs two trivial queries against the same sample "users" table. In this case, the class will happily connect to MySQL only once, which is the expected behavior. The script looks like this: <?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(); } There you have it. Thanks to the inclusion of a static variable, now any object spawned from the previous "MySQLiWrapper" class will establish only a single connection to MySQL. Hopefully, this final example will spark your own inspiration and get you started using static properties in all sorts of creative ways. Final thoughts In this third part of the series, I showed how to use another static property within the previous MySQL diver to connect "more cleverly" to the database server. Once again, this example demonstrated how powerful a property like this can be when utilized in an effective manner. In the last chapter of the series I'm going to teach you how to get the same benefit when connecting to MySQL via a static, local variable, instead of explicitly using a class property. Don't miss the upcoming tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|