Tuesday 6 April 2010

How __autoload() does?

Autoload is a new feature introduced in PHP5 that you don't have to explicitly require or include a PHP script file that contains the class being used any more but it will be automatically loaded or included when needed.

For example, with PHP4 you would have to write something like this:

require_once("foo.php"); // foo.php contains the class Foo
myFoo = new Foo();

Every time you need to create an object of some class you have to include/require the particular PHP file
that contains that class.
It can be a challenge to manage the whole lot of include or require lines as well.
That's where the autoload feature of PHP5 kicks in.

Instead of including a particular PHP script every time we need it, we create a very simple function at the beginning of the current file so that PHP automatically knows what file to include when we need a particular class.
For example:
function __autoload($className)
{
    require_once 'includes/classes/'. $className. '.php';
}

$obj1 = new MyNewClass1(); // PHP automatically requires 'includes/classes/MyNewClass1.php'
$obj2 = new MyNewClass2(); // PHP automatically requires 'includes/classes/MyNewClass2.php'

2 comments:

  1. what happens if we want to structure our includes or we want to split whole application into modules and want to keep all libraries related to module in a different folder.

    ReplyDelete