开发者

Instantiate new object from variable [duplicate]

开发者 https://www.devze.com 2023-03-05 07:10 出处:网络
This question already has answers here: Call to a member function on a non-object [duplicate] (8 answers)
This question already has answers here: Call to a member function on a non-object [duplicate] (8 answers) Closed 10 years ago.

I'm using the following class to autoload all my classes. This class extends the core class.

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

I instantiate that class in the __construct() of my core class:

public function __construct() {
    $autoloader = new classAutoloader();
}

Now I want to be able to instantiate objects in the loader class like this:

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

But I get the following error calling $core-template like this:

require 'includes/classes/core.php';
$core = new SH_Core();

if (isset($_GET['p']) && !empty($_GET['p'])) {
    $core->template->loadPage($_GET['p']);
} else {
    $core->te开发者_如何学Gomplate->loadPage(FRONTPAGE);   
}

The error:

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

It autoloads the classes but just doesn't initiate the object because using the following code it works without any problems:

public function __construct() {
    $autoloader = new classAutoloader();

    $this->database = new SH_Database();
    $this->template = new SH_Template();
    $this->session = new SH_Session();
}


Have you tried:

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

instead?


I solved it using:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号