Wednesday, 28 September 2016

php - Instantiate new object from variable

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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...