2011-05-11 154 views
4

我正在使用以下类来自动加载所有的类。这个类扩展了核心类。从变量实例化新对象

class classAutoloader extends SH_Core { 

    public function __construct() { 
     spl_autoload_register(array($this, 'loader'));  
    } 

    private function loader($class_name) { 
     $class_name_plain = strtolower(str_replace("SH_", "", $class_name)); 
     include $class_name_plain . '.php'; 
    } 
} 

我实例化类在我的核心类的__construct()

public function __construct() { 
    $autoloader = new classAutoloader(); 
} 

现在我希望能够实例化的装载机类对象是这样的:

private function loader($class_name) { 
    $class_name_plain = strtolower(str_replace("SH_", "", $class_name)); 
    include $class_name_plain . '.php'; 
    $this->$class_name_plain = new $class_name; 
} 

但我得到以下错误调用$core-template像这样:

require 'includes/classes/core.php'; 
$core = new SH_Core(); 

if (isset($_GET['p']) && !empty($_GET['p'])) { 
    $core->template->loadPage($_GET['p']); 
} else { 
    $core->template->loadPage(FRONTPAGE); 
} 

错误:

Notice: Undefined property: SH_Core::$template in /home/fabian/domains/fabianpas.nl/public_html/framework/index.php on line 8
Fatal error: Call to a member function loadPage() on a non-object in /home/fabian/domains/fabianpas.nl/public_html/framework/index.php on line 8

它自动加载的类,但因为使用下面的代码它的工作没有任何问题只是没有启动对象:

public function __construct() { 
    $autoloader = new classAutoloader(); 

    $this->database = new SH_Database(); 
    $this->template = new SH_Template(); 
    $this->session = new SH_Session(); 
} 
+0

该功能你得到一个错误。为了帮助解决这个错误,我们需要导致错误的代码。 – 2011-05-11 12:23:54

+0

你的错误和散文是指在给定的代码中没有代表的东西。提供一个_testcase_。 – 2011-05-11 12:26:10

回答

8

你试过:

$this->$class_name_plain = new $class_name(); 

取而代之?

0

我解决它使用:对于是不是在你给我们的代码

private function createObjects() { 
    $handle = opendir('./includes/classes/'); 
    if ($handle) { 
     while (false !== ($file = readdir($handle))) { 
      if ($file != "." && $file != "..") { 
       $object_name = str_replace(".php", "", $file); 
       if ($object_name != "core") { 
        $class_name = "SH_" . ucfirst($object_name); 
        $this->$object_name = new $class_name(); 
       } 
      } 
     } 
     closedir($handle); 
    } 
}