因此,在PHP中,我知道全局命名空间中存在静态类,因此在调用它们时会导致开销。
但是当你将一个本地类变量或一个局部变量赋给该静态类时会发生什么?是否删除了全局引用的开销?
在我的具体案例中,我使用的是静态单例。
class Registry {
public static $user;
public static $DB;
public static $config;
public static $user_data;
private static $initialized = FALSE;
public static function init($config) {
if (!registry::$initialized) {
registry::$config = $config;
registry::$DB = new db($config['mysql']);
registry::$user = new user();
registry::$initialized = TRUE;
} else {
throw new Exception('Registry has already been initialized.');
}
}
}
现在,为了使问题更清楚,将另一个类中的注册表映射到类变量/局部变量以进行连续的函数调用是否有益?
class SomethingSomethingDarkSide {
private $registry;
private $db;
private $config;
public function __construct() {
$this->registry = Registry;
$this->db = Registry::$db;
$this->config = Registry::$config;
}
}
由于静态成员现在在初始化之后被分配给一个类变量,因此调用使用这些类变量的连续方法会消除静态成员持久存在的全局命名空间的开销吗?
编辑:在这种情况下,请删除Singleton的想法。问题更多的是我们是否必须在每次引用变量后查找Registry
。
IE:
$registry = Registry;
$registry::doSomething();
$registry::doSomething2();
$registry::doSomething3();
VS
Registry::doSomething();
Registry::doSomething2();
Registry::doSomething3();
OR:
class Test {
public static function sayHi() {
echo 'Hi';
}
}
$test = Test;
echo $test::sayHi(); // This being done multiple times versus
echo Test::sayHi(); // That being done multiple times
答案 0 :(得分:0)
我认为您最初的问题是您的Singleton实现不正确。请改为查看此代码:
class Registry {
private static $instance = null;
private $user;
private $DB;
private $config;
private $user_data;
public static function getInstance($config) {
if (self::$instance === null)
{
self::$instance = new self($config);
}
return self::$instance;
}
private function __construct($config) {
$this->$config = $config;
$this->$DB = new db($config['mysql']);
$this->$user = new user();
}
public function doThing() {
}
}
$registry = Registry::getInstance($config);
$registry->doThing();
由于构造函数是私有的,因此获取Registry
类的新实例的唯一方法是使用公共静态方法getInstance
。
从那时起,您有一个$registry
变量指向Registry
类的实例(如果它不是您想要的那么我就不明白为什么您使用的是Singleton图案...)
我认为非常接近你想要的东西:
$registry = Registry;
$registry->doSomething();
$registry->doSomething2();
$registry->doSomething3();