Section 3.19. __autoload()


3.19. __autoload()

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 (like other examples shown in Chapter 2, due to it being spread across more than one file 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.




    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net