如何使对象全局可访问?
问题描述:
我有这样的代码:如何使对象全局可访问?
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.
我认为问题出在自身:: $ DB =新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();
感谢它的工作! – 2010-05-08 18:21:11
使用非静态'$ db'的静态'$ _instance'似乎没什么意义。 – Tgr 2010-05-08 18:52:20
@Tgr:'$ db'是实例本地的,但只有其中一个。它以相同的方式工作。 – 2010-05-08 19:09:42