Without a doubt, one of the most useful PHP 5 functions in the “magic” category is the handy “__autoload().” As you may have guessed, when properly implemented, this function permits you to load automatically classes whose definitions haven’t been explicitly included into a given script. This ability is indeed remarkable (despite the disparate opinions of other developers), since it’s possible to build, for instance, bootstrap files that load classes in a transparent manner without having to directly code lots of PHP includes. Of course, the “__autoload()” function isn’t the only one that can be used for including classes automatically; there are others that are even more powerful. One such example is the “spl_autoload_register()” function provided by the Standard PHP Library, which allows you to register custom functions or methods for performing this process in a more thorough way. However, for now I’ll keep this tutorial focused on the advantages to using the “__autoload()” function only. So, with that goal in mind, what I’m going to do next will consist of defining another example class, which will be “autoloaded()” by a script which will be coded afterwards. That being explained, here’s the full source of the aforementioned sample class, called “User” once again. Check it out: class User { private $name = 'Alejandro'; private $email = 'alejandro@domain.com';
// constructor public function __construct($name = '', $email = '') { if ($name != '') { $this->name = $name; } if ($email != '') { $this->email = $email; } }
// get user's name public function get_name() { return $this->name; }
// get user's email address public function get_email() { return $this->email; }
function __toString() { return 'Name: ' . $this->name . ' Email: ' . $this->email; } }
As you can see, the previous “User” class has nothing special; it's useful only for storing the full name and email address of a user and retrieving the values assigned to these properties via its “__toString()” method. This method is also a magic function, but for the sake of brevity it won’t be covered in this article series. So far, everything looks good, since at this point there’s a class available for testing the real functionality of the “__autoload()” function. But wait a minute! What functionality am I’m talking about if the function in question hasn’t been implemented yet? Well, don’t worry, because in the next section I’m going to do that, and I'm also going to demonstrate how to automatically load the previous “User” class within a simple script. As I just mentioned, all of these tasks will be performed in the following segment, so to get there, click on the link that appears below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|