Loading classes automatically: taking a first look at the “__autoload()” PHP 5 magic function As I explained in the previous section, PHP 5 comes equipped with the “__autoload()” magic function for automatically including all of the source classes required by a specific application into client code. In others words, the PHP 5 interpreter will simply invoke this function automatically when a determined script attempts to utilize a class that hadn’t been defined previously. This means that it’s possible to implement this function in such a way that it includes the source file of a given class when not available. Sounds rather confusing, doesn't it? Well, fear not. In order to clarify how the “__autoload()” function works, below I rewrote the script that you saw in the prior section, this time using the mentioned function. Please, have a close look at the following code sample: // include required classes 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(); } If you study in detail the above example, you’ll understand very easily how the “__autoload()” PHP function does its business. As you can see, in this case the function in question will try to include two different files, called “mysql.php” and “result.php” respectively, whenever the pertinent definitions of the “MySQL” and “Result” classes are required by this sample database-driven application. In this way it implements a powerful mechanism for loading all the source classes demanded by a certain script. Of course, the major benefit of using this function is that’s no longer necessary to use a PHP include for each class that needs to be utilized. The “__autoload()” function will perform this task behind the scenes, so you won’t have to be concerned about this process. Pretty useful, right? Besides, it’s easy to see that all the scripts that work with this function will obviously need to implement it concretely. This can be a bit annoying, but I think that you’ll be more than happy using it within your PHP 5-based applications. Now that you've hopefully grasped the logic in utilizing the “__autoload()” PHP 5 magic function, it's time to read the last section of this tutorial, where I’ll be listing the complete definitions of the two practical examples that I developed earlier. You can evaluate adequately the pros and cons in loading source classes with conventional includes and with the “__autoload()” function. Go ahead and read the next few lines. I’ll be there, waiting for you.
blog comments powered by Disqus |
|
|
|
|
|
|
|