Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • __autoload function in php

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 152
    Comment on it

    A function in PHP which starts with a double underscore”__” are called magic functions in PHP. __autoload functions is used to add very large number of include statements automatically without the programmer.

    For instance:

    include class/class.A.php;
    include class/class.B.php;
    include class/class.C.php;
    
    $x = new A;
    $y = new B;
    $z = new C;

    In the above code we have to include each of three different class files separately because we are creating an instance of each class. Although, we are allowed to have multiple classes in one source file but here we are assuming that the developers are defining only one class per source file- which is a good practice when writing object oriented programs.

     

    Here we have just included three different classes but if we need to use 20 or more different classes within one file, writing out each include statement can be typical. And this is exactly the problem which is solved by the PHP __autoload function- as it allows to load the classes for us automatically.

     

    The above code can be rewritten as:

    function __autoload($class_name)
    {
    	require_once./class/class/.$class_name..php;
    }
    
    $x = new A;
    $y = new B;
    $z = new C;

     

    When does the __autoload function actually get called?

    PHP will make a call to the __autoload function each time it does not recognize a class name. In the code above, the __autoload function will be called 3 times, because PHP will not recognize the A, B, C classes. We can also see that the __autoload function takes the class name as a parameter (the $class_name variable). PHP passes the variable to the function whenever it finds that it doesn't recognize the class name that is being used in the given statement. For instance, when PHP sees the $x = new A; line, it does not recognize the A class because the A class was never included or “required” as part of the current line. So, PHP then passes the “A” class to the __autoload function, and if the class file is found by the autoload function then it is included by the “require_once” statement. The assumption made here is that the class folder is in the same directory as the current file.

     

    The __autoload function is called any number of times when a reference to an unknown class is made in our code.

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: