Comparing two different approaches for loading source classes: listing the previous code samples As I promised in the previous section, here is the complete source code corresponding to the two examples that you learned earlier, where the first one uses conventional PHP includes to load the pertinent “MySQL” and “Result” classes, and the second one utilizes the handy “__autoload()” function: (example using conventional PHP includes) try{ // include required classes require_once 'mysql.php'; require_once 'result.php'; // connect to MySQL $db=new MySQL(array // fetch users from database table $result=$db->query('SELECT * FROM users ORDER BY id'); // display user data while($row=$result->fetch()){ echo 'Id: '.$row['id'].' First Name: '.$row['firstname'].' Last Name: '.$row } } catch(Exception $e){ echo $e->getMessage(); exit(); } // example using the magic '__autoload()' function function __autoload($className){ require_once $className.'.php'; } try{ // connect to MySQL $db=new MySQL(array // fetch users from database table $result=$db->query('SELECT * FROM users ORDER BY id'); // display user data while($row=$result->fetch()){ echo 'Id: '.$row['id'].' First Name: '.$row['firstname'].' Last Name: '.$row } } catch(Exception $e){ echo $e->getMessage(); exit(); } From this point on, it’s up to you decide which approach fits your specific needs better when it comes to loading all the source classes required by a specific PHP 5 application. I’ve been using the “__autoload()” magic function for one year or so, and I consider it a superior option over common PHP includes. Final thoughts In this initial article of the series, I introduced the basics of using the “__autoload()” magic function that comes bundled with PHP 5. As you saw, it can be really useful for loading automatically all the source classes required by a given application. However, this function has an important downside, since any exception thrown when attempting to load a concrete class simply can’t be caught inside a “try-catch” block. However, there are some workarounds that come in handy for solving this issue. And I’ll be showing them in the next part of the series. Now that you’ve been warned, you won’t want to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|