Saturday 31 August 2013

Easy way of calling classes in Core PHP

When we do large projects, we did have lot of class libraries associated with our project. So whenever we want to use a class in our code page, You have to include that class in the top of the page.
But rather than this php has given an easy way to do this named    _autoload(); function...

Below Iam giving code for this:-

<?php

date_default_timezone_set("Asia/Calcutta");
define("CONST_BASEDIR",dirname(__FILE__));
define('CONST_LIBRARY_FOLDER',CONST_BASEDIR.'/libs');// class files placed folder
$_SESSION['CONST_BASEDIR']=CONST_BASEDIR;
error_reporting(E_ALL & ~ E_NOTICE);
function __autoload($className){

if(!class_exists($className)){
$parts = explode("_",$className);
if(count($parts)==1){
$folder = CONST_LIBRARY_FOLDER."/".$className.".php";
}else{
$folder = CONST_LIBRARY_FOLDER."/";
for($i=0;$i<count($parts)-1;$i++){
$folder.= strtolower($parts[$i]);
$folder.="/";
}
$folder.=$parts[count($parts)-1].".php";

}
include_once($folder);
}
}
?>
Just save the above page as autoload.php and include in every page.

So after that You didn't want to include any class seperately, you just want to call corresponding class like


$obj=new User();//creating object

$userdetails=$obj->getdetails();// calling function with class object


So when doing this automatically _autoload function will look into the libraray folder for User.php file and it will include it.... and will works fine...............................