Programming Tutorials

__autoload() METHOD in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

When writing object-oriented code, it is often customary to put each class in its own source file. The advantage of this is that it's much easier to find where a class is placed, and it also minimizes the amount of code that needs to be included because you only include exactly the classes you need. The downside is that you often have to include tons and tons of source files, which can be a pain, often leading to including too many files and a code-maintenance headache.

__autoload() solves this problem by not requiring you to include classes you are about to use. If an __autoload() function is defined (only one such function can exist per application) and you access a class that hasn"t been defined, it will be called with the class name as a parameter. This gives you a chance to include the class just in time. If you successfully include the class, your source code continues executing as if the class had been defined. If you don't successfully include the class, the scripting engine raises a fatal error about the class not existing.

Here's a typical example using __autoload():

MyClass.php:

<?php
class MyClass {
function printHelloWorld()
{
print "Hello, World\n";
}
}
?>

general.inc:

<?php
function __autoload($class_name)
{
require_once($_SERVER["DOCUMENT_ROOT"] . "/classes/$class_name.php");
}
?>

main.php:

<?php
require_once "general.inc";
$obj = new MyClass();
$obj->printHelloWorld();
?>

Note: This example doesn't omit the PHP open and close tags and, thus, not being a code snippet.

So long as MyClass.php exists in the classes/ directory inside the document root of the web server, the script prints

Hello, World

Realize that MyClass.php was not explicitly included in main.php but implicitly by the call to __autoload(). You will usually keep the definition of __autoload() in a file that is included by all of your main script files (similar to general.inc in this example), and when the amount of classes you use increases, the savings in code and maintenance will be great.

Note:

Although classes in PHP are case-insensitive, case is preserved when sending the class name to __autoload(). If you prefer your classes" file names to be case-sensitive, make sure you are consistent in your code, and always use the correct case for your classes. If you prefer not to do so, you can use the strtolower() function to lowercase the class name before trying to include it, and save the classes under lowercased file names.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)