Instantiate new object from variable [duplicate]
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);
}
}
精彩评论