You are hereDevelopment / PHP / Dynamically loading classes

Dynamically loading classes


By maho - Posted on 20 March 2008

class test{
    var $_tvar="123";
}
$ttmp = "test";
$dynCls = new $ttmp();
echo $dynCls->_tvar;

This can easily be used to pickup classes from files in a specific folder.

if(is_dir($dir)) {
  if($dh = opendir($dir)) {
    while (($dObj = readdir($dh)) !== false) {
      if($dObj{0}!="." && is_dir($dir.$dObj)) {
        if($fh = opendir($dir.$dObj)){
          while (($fObj = readdir($fh)) !== false) {
            if($fObj{0}!="." && is_file($dir.$dObj."/".$fObj)) {
              if(substr($fObj,0,strrpos($fObj,"."))== $dObj){ 
                include_once($dir.$dObj."/".$fObj); 
                ....some code to get the $classname... 
                $classname = new $_mObj; 
              }
            } 
          } 
        } 
        closedir($fh); 
      } 
    } 
    closedir($dh); 
  } 
}

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.