Sunday, March 29, 2009

Autoloading Objects in php

You may have one php source file per class definition. For example Class1.php file contains Class1 definition, Class2.php contains Class2 definition, Class3.php conatins Class3 definition, etc. So to use those classes under different files you need to write a series of includes/ requires statements. In case of class/variable/method is not found it will search within the files mentioned inside includes/requires.

Sometimes so many includes/requires may be of pain tasks.

With php 5.0, you can avoid to include a list of includes/requires. You can use __autoload function and with this __autoload function the file will be automatically called in case you are trying to use a class/interface which hasn't been defined yet.

Note that exception thrown inside __autoload function can't be caught by catch block.

Below is an example of __autoload function.
My Class1.php

<?php
class Class1{
public $a=1000;
}
?>

My Class2.php

<?php
$test1="Momin";
$test2="Arju";
class Class2{
function display(){
echo "This is include/require test";
}
}
?>

My autoloading.php

<?php
function __autoload($className){
require_once $className.'.php';
}
$class1Instance=new Class1();
echo $class1Instance->a;
echo "<br />";
$class2Instance=new Class2();
$class2Instance->display();
?>

If I run autoloading.php in the browser it will show,
1000
This is include/require test

Related Documents
http://arjudba.blogspot.com/2009/03/requireonce-and-includeonce-in-php.html
http://arjudba.blogspot.com/2009/03/require-and-include-parameter-in-php.html 

No comments:

Post a Comment