Before I start explaining how to use the “spl_autoload()” and “spl_autoload_register()” functions to build a more complex file loading program in PHP 5, first it would be helpful to reintroduce the example developed in the previous article. It was aimed at demonstrating how to create this kind of application by giving a basic implementation to the “__autoload()” function. Here is the signature of the sample “User” class that needs to be included in a fictional application: 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 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; } } And here’s the file loading script that uses the “__autoload()” function for including the “User” class that you just saw: // define a generic exception handler function function exception_handler($e) { echo $e->getMessage(); }
set_exception_handler('exception_handler'); function __autoload($class) { $file = $class . '.php'; if(!file_exists($file)){ return eval("class {$class}{public function __construct(){throw new Exception('Class {$class} not found!');}}"); } require_once($file); }
// create instance of User class $user = new User(); // display user data echo $user; As depicted above, it’s obviously mandatory to give a concrete implementation to the “__autoload()” PHP function when dynamically loading a required class. Of course, it’s possible to extend the functionality of the example shown before, but for the sake of brevity I’ll keep it that simple for now. At this stage, you've hopefully grasped the logic that stands behind creating class loaders with the “__autoload()” function. But as I stated previously, it needs to be implemented from scratch. However, PHP 5 introduced the “spl_autoload()” function, which offers a default implementation for “__autoload().” Does all this sound a bit confusing to you? Don’t worry; in the following section I’m going to set up another code sample, which will clearly demonstrate the usage of the “spl_autoload()” function. To see how this brand new example will be developed, click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|