How to use autoloading object in php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to use autoloading object in php

Post by Neo » Mon Mar 01, 2010 12:17 am

When writing the PHP that powers TempServers, I wrote the core functions into classes for better organization and efficiency. To make things further organized, each class is stored in individual source files, no matter how small. The problem here is keeping track of which classes are used where, in order to include the appropriate source files. Fortunately, PHP 5 offers a solution: autoloading.

This comes in the form of the __autoload function which automatically gets called if a class is called that does not exist. Here's what it looks like:

Code: Select all

function __autoload($class) {
    require_once(strtolower($class) . '.class.php');
} 
Usage
Place each PHP class in individual files named after the class followed by .class.php (Example: class MyClass goes in a file named myclass.class.php).
Include the code snipped above into any file that might use one of your classes.

For more details, check out the PHP manual: http://www.php.net/manual/language.oop5.autoload.php
Post Reply

Return to “PHP & MySQL”