忽略命名空間等任何一個可以解釋爲什麼我不能返回對我的靜態數組的引用?這個班級實際上是一個吸氣和二傳手。我想使用靜態方法,因爲在整個應用程序生命週期中,類永遠都不需要再次實例化。PHP通過引用返回靜態變量
我明白我在做什麼可能只是「不好的做法」 - 任何關於此事的更多知識將不勝感激。
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");
但我只是找回當初。
您可以通過註冊表訪問::您是否正確地使用它添加($鍵,$商店) –
?見[php.net參考資料](http://php.net/manual/en/language.references.return.php) –
@AlvinWong更新我的問題與我如何使用它。 –