php - 从变量实例化新对象

标签 php

<分区>

我正在使用以下类来自动加载我的所有类。这个类扩展了核心类。

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();
}

最佳答案

你试过吗:

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

代替?

关于php - 从变量实例化新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5964113/

相关文章:

php - 退出 php 命令而不触发关闭函数

php - phpredis 库中 Redis 函数 ZUNIONSTORE() 的方法是什么?

php - PDO异常错误

javascript - 从 JSON 到 Actionscript

javascript - wordpress 安全中的 Ajax

php - 从 Android -> PHP -> MYSQL 插入多个条目

php - 唯一约束返回类型不匹配

php - NuSoap soapClient 调用出现 "Premature end of data in tag html"错误

javascript - 使用 dataURL 发送变量

php - PHP 中的静态类是不好的做法吗?