忽略命名空间等任何人都可以解释为什么我不能返回对我的静态数组的引用吗?实际上,该类是一个 getter 和 setter。我想使用静态方法,因为在整个应用程序生命周期中永远不需要再次实例化该类。
我知道我正在做的事情可能只是“不好的做法” - 任何关于此事的更多知识将不胜感激。
namespace xtend\core\classes;
use xtend\core\classes\exceptions;
class registry {
private static $global_registry = array();
private function __construct() {}
public static function add($key, $store) {
if (!isset(self::$global_registry[$key])) {
self::$global_registry[$key] = $store;
} else {
throw new exceptions\invalidParameterException(
"Failed to add the registry. The key $key already exists."
);
}
}
public static function remove($key) {
if (isset(self::$global_registry[$key])) {
unset(self::$global_registry[$key]);
} else {
throw new exceptions\invalidParameterException(
"Cannot remove key $key does not exist in the registry"
);
}
}
public static function &get($key) {
if (isset(self::$global_registry[$key])) {
$ref =& self::$global_registry[$key];
return $ref;
} else {
throw new exceptions\invalidParameterException(
"Cannot get key $key does not exist in the registry"
);
}
}
}
像这样使用它
$test = array("my","array");
\xtend\core\classes\registry::add("config",&$test);
$test2 =& \xtend\core\classes\registry::get("config");
$test2[0] = "notmy";
print_r($test);
你会认为我会回来
array("notmy","array");
但我只取回原件。