【发布时间】:2012-10-10 19:27:51
【问题描述】:
忽略命名空间等任何人都可以解释为什么我不能返回对我的静态数组的引用吗?实际上,该类是一个 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");
但我只是拿回原件。
【问题讨论】:
-
可以通过registry::add($key, $store)访问
-
你用对了吗?见php.net reference
-
@AlvinWong 用我的使用方式更新了我的问题。
-
@JonathanTizard 也许你没有以正确的方式制作
add:Passing by reference
标签: php reference static return