Tuesday, March 5, 2013

use why __autoload function in php with example

A simple example of using PHP's __autoload function is like so:
function __autoload($classname) {
    include("classes/$classname.class.php");   
}
If you then ran the following code
$testclass= new testclass;
and the "testclass" class had not yet been defined, __autoload is called passing "
testclass
" as the parameter. The example __autoload function then includes the appropriate file which as defined in the above example would be "classes/
testclass.class.php", although you would change this to 
whatever your naming convention and location of class files is.
Note that there's no need to use include_once() or require_once() to include the files - just include() or require() will do. This is because __autoload won't need to be called again if you create another instance of the class because the class is already defined. The following illustrates this:
echo "new testclass<br />";
$testclass= new testclass;
echo "new testclass<br />";
$testclass= new testclass;
echo "new bar<br />";
$bar = new bar;

function __autoload($classname) {
    echo "autoload $classname<br />";
    include("classes/$classname.class.php");
}
The output from the above would be:
new testclass
autoload testclass
new testclass
new bar
autoload testclass
This shows that __autoload() was only called each time a class that wasn't already defined was used. Because the "foo" class had aready been defined the second time we create a
testclass
object the class was already defined and did not need to be loaded again.
Using the autoload function in PHP is really useful because you don't need to bother including all the necessary class files at the start of each script: they will be automatically loaded as and when required.

No comments:

Post a Comment