我正在使用以下类来自动加载我的所有课程。这个类扩展了核心类。
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();
}
现在我希望能够在loader类中实例化对象:
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);
}
错误:
注意:第8行的/home/fabian/domains/fabianpas.nl/public_html/framework/index.php中未定义的属性:SH_Core :: $ template 致命错误:在第8行的/home/fabian/domains/fabianpas.nl/public_html/framework/index.php中的非对象上调用成员函数loadPage()
它自动加载类但不启动对象,因为使用以下代码它可以正常工作:
public function __construct() {
$autoloader = new classAutoloader();
$this->database = new SH_Database();
$this->template = new SH_Template();
$this->session = new SH_Session();
}
答案 0 :(得分:8)
你试过了吗?
$this->$class_name_plain = new $class_name();
代替?
答案 1 :(得分: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);
}
}