Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate new object from variable [duplicate]

Tags:

php

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->template->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();
}
like image 836
Fabian Avatar asked May 11 '11 12:05

Fabian


1 Answers

Have you tried:

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

instead?

like image 179
onteria_ Avatar answered Oct 06 '22 00:10

onteria_