2011-05-11 82 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); 
    } 
}