我正在使用以下类来自动加载我所有的类。此类扩展了核心类。
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);
}
错误:
注意:未定义的属性:SH_Core::$template 在/home/fabian/domains/fabianpas.nl/public_html/framework/index.php 第 8
行 致命错误:在第 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();
}
你试过吗:
$this->$class_name_plain = new $class_name();
相反?
我使用以下方法解决了它:
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);
}
}