how does autoload functions in php

Discussion in 'PHP' started by vaibhav.bagade, Nov 18, 2012.

  1. #1
    I am new to PHP.
    Can any explain how does this code actually works
    
    function autoload($class)
    {
        require('classes/' . $class . '.class.php');
    }
    
    // automatically loads all needed classes, when they are needed
    spl_autoload_register("autoload");
    
    PHP:
    Thanks :)
     
    vaibhav.bagade, Nov 18, 2012 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    EricBruggema, Nov 19, 2012 IP
  3. arsalankhan

    arsalankhan Peon

    Messages:
    66
    Likes Received:
    0
    Best Answers:
    6
    Trophy Points:
    0
    #3
    spl_autoload_register registers a callback function to include a class incase we have not included it, so in your code whenever an unregistered class is called PHP interpreter will call the autoload function and then the autoload function will check the classes directory to find a file having classname as its filename, so "new UndefinedClass()" will check for UndefinedClass.php in the classes directory.

    Please note: You can create a function __autoload() if you don't want to use the spl_autoload_register function and you should be using __autoload() only because spl_autoload_register should be used only when you want to add more than two functions in __autoload stack.
     
    arsalankhan, Nov 19, 2012 IP