[英]how to make objects globally accessible?
我有此代码:
class IC_Core {
/**
* Database
* @var IC_Database
*/
public static $db = NULL;
/**
* Core
* @var IC_Core
*/
protected static $_instance = NULL;
private function __construct() {
}
public static function getInstance() {
if ( ! is_object(self::$_instance)) {
self::$_instance = new self();
self::initialize(self::$_instance);
}
return self::$_instance;
}
private static function initialize(IC_Core $IC_Core) {
self::$db = new IC_Database($IC_Core);
}
}
但是当我想通过以下方式访问IC_Database时:
$IC = IC_Core::getInstance();
$IC->db->add() // it says that its not an object.
我认为问题出在self :: $ db = new IC_Database($ IC_Core);
但我不知道如何使它工作。
有人可以帮我吗=)
谢谢!
在我看来, initialize
应该是一个实例方法,而不是静态方法。 然后应该使用$this->db
而不是self::$db
。
public static function getInstance() {
if ( ! is_object(self::$_instance)) {
self::$_instance = new self();
self::$_instance->initialize();
}
return self::$_instance;
}
private function initialize() {
$this->db = new IC_Database($this);
}
您甚至可以将initialize
方法的内容放入构造函数中,这样就不必担心调用它。
$ db属性被声明为static
因此您必须使用双冒号访问它。 箭头符号仅适用于非静态属性。
$IC = IC_Core::getInstance();
IC_Core::$db->add();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.