Jon*_*ard 5 php static return reference
忽略命名空间等任何人都可以解释为什么我不能返回对我的静态数组的引用?实际上,该类是一个 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"
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它
$test = array("my","array");
\xtend\core\classes\registry::add("config",&$test);
$test2 =& \xtend\core\classes\registry::get("config");
$test2[0] = "notmy";
print_r($test);
Run Code Online (Sandbox Code Playgroud)
你会认为我会回来
array("notmy","array");
Run Code Online (Sandbox Code Playgroud)
但我只是找回原来的。
执行摘要:
class Registry {
private static $global_registry = array();
public static function Add($key, &$value){
static::$global_registry[$key] =& $value;
}
public static function &Get($key){
return static::$global_registry[$key];
}
public static function Remove($key){
unset(static::$global_registry[$key]);
}
}
$test = array("my", "array");
Registry::Add("config", $test);
$test2 =& Registry::Get("config");
$test2[0] = "notmy";
var_dump($test);
Run Code Online (Sandbox Code Playgroud)
一旦您了解了它的工作原理,它就变得非常简单:
首先,函数add必须按引用传递,否则在函数中看到的值甚至不是您传入的值。
其次,在 中存储值时$global_registry,我们必须通过引用赋值。否则,存储的值甚至不是函数中看到的值。
第三,我们必须通过在函数声明中放置一个&符号来按引用返回。您已经完成了此操作,除了以下代码:
$ref =& self::$global_registry[$key]; // redundant line
return $ref;
Run Code Online (Sandbox Code Playgroud)
与此代码相同:
return self::$global_registry[$key];
Run Code Online (Sandbox Code Playgroud)
因为在行中public static function &get,我们已经声明返回值是一个引用。
$test2 =& Registry::Get("config");
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,整个链条必须通过引用。如果其中任何一个步骤没有通过引用完成,那么它就不会起作用。