how does php autoloader works how does php autoloader works php php

how does php autoloader works


The PHP autoloader is just a mechanism to include a file when a class is constructed.

If you put all your classes in 1 file, you dont need an autoloader. Of course, when programming OO you give every class its own file, and that's where the autoloader comes in.

Some examples:

class AutoLoader{    public function __construct()  {    spl_autoload_register( array( $this, 'ClassLoader' ));  }  public function ClassLoader( $class )  {        if( class_exists( $class, false ))      return true;    if( is_readable( 'path_to_my_classes/' . $class . '.php' ))          include_once 'path_to_my_classes/' . $class . '.php'  }}$autoloader = new AutoLoader();

What happens here is that when the autoloader class is created, the class method Classloader is registered as a autoloader.

When a new class is created, the Classloader method first checks if the file for the class is already loaded. If not, the class is prepended with a path and extended with an extension. If the file is readable, it is included.

Of course, you can make this very sophisticated. Let's look at an example with namespaces and a mapper. Assume we are in the autoloader class:

  private $mapper array( 'Foo' => 'path_to_foo_files/', 'Bar' => 'path_to_bar_files/');  public function ClassLoader( $class )  {        if( class_exists( $class, false ))      return true;    // break into single namespace and class name    $classparts = explode( '\\', $class );     $path = $this->mapper[$classparts[0]];    if( is_readable( $path . $classparts[1] . '.php' ))          include_once $path . $classparts[1] . '.php'  }

Here, the classname is split in the namespace part and the classname parts. The namespace part is looked up in a mapper array and that path is then used as include path for the php file.

These are just examples to demonstrate what can be done with autoloader. For production there is some more work to be done, error checking for example.