微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 从变量实例化新对象

参见英文答案 > Call to a member function on a non-object                                     8个
我正在使用以下类来自动加载我的所有类.这个类扩展了核心类.

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

错误

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

代替?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐