Home arrow PHP arrow Page 3 - Using the _autoload() Magic Function to Build Loader Appps in PHP

Loading files with the autoload PHP magic function - PHP

Welcome to the sixth part of an eight-part series that shows you how to build file loader applications in PHP. In this part I will discuss how to build a helpful file loading application by taking advantage of the nifty “__autoload()” magic function.

TABLE OF CONTENTS:
  1. Using the _autoload() Magic Function to Build Loader Appps in PHP
  2. Review: building a file loader class the old way
  3. Loading files with the autoload PHP magic function
  4. Implementing an enhanced exception mechanism
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
June 24, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
  

Undeniably, one of the most useful features incorporated into PHP 5, aside from its solid object model, is the set of magic functions, which permit you to automatically load a determined file. 

As you may guess, in this particular case I’m talking about the “__autoload()” function. When this function is implemented, it allows you to build file loading scripts very quickly. 

To demonstrate a simple usage of this function, I’m going to define a sample class called “User,” which will store some data about a specific user: their first and last names, and their email address. 

Then, with that class available for testing purposes, I’m going to show how to include it in a script by directly using the “require_once()” function, and finally by means of the “__autoload()” function. 

That being explained, here’s how the “User” class looks:

 

class User

{

private $name = 'Alejandro';

private $email = 'Gervasio';

 

// 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;

}

}

 

So far, nothing spectacular is going on here, right? As you can see, the above “User” class has some simple setter and getter methods that permit you to set and retrieve the first and last names of a given user, as well as their email address. 

In addition, the “__toString()” magic method allows you to display the value of these properties very easily, but the rest of the class code is extremely easy to follow. 

So far, so good. Now that the previous “User” class has been properly defined, say that you need to use it within a simple program. In a typical case, to do this you’d use a script similar to the one below:

 

// loading the user class using require_once()

require_once 'user.php';

// create instance of User class

$user = new User();

// display user data

echo $user;

 

Again, this example doesn’t bear any further discussion, because of its simplicity. However, see what happens when the “User” class is included via the “__autoload()” function:

 

// loading the user class using the __autoload() function

function __autoload($class)

{

$file = $class . '.php';

if (file_exists($file))

{

require_once($file);

}

}

// create instance of User class

$user = new User();

// display user data

echo $user;

 

Definitely, things have become much more interesting at this point. The class has now been included in the previous script by implementing the “__autoload()” function in a pretty basic way. Though small, this is certainly an improvement that leads toward loading files automatically.  

What’s more, it’s possible to make the “__autoload()” function throw an exception if the targeted file can’t be found. This feature has been implemented by the following script. Take a look at it, please:

 

// example on loading a class using the __autoload() function triggering an exception

 

// 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)){

eval("class $class {}");

throw new Exception('Class ' . $class . ' not found.');

}

require_once($file);

}

 

// create instance of User class

$user = new User();

// display user data

echo $user;

 

Well, admittedly the “eval()” function called when autoloading the “User” class isn’t the most elegant solution for triggering an exception, but it does a decent job when it comes to tying an error mechanism to the “__autoload()” function. 

However, it’s possible to polish the definition of this function a bit more by creating a more efficient exception handling script. Therefore, I’m going to finish this article by showing you how to develop such a script in a few easy steps. 

Now, please click on the link shown below and read the section to come.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: