Summary:
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);
It is really very simple, once you understand how it works:
Firstly, the add function must follow the link , otherwise the value that is visible in the function is not even the value that you passed.
Secondly, when saving the value in $global_registry we must assign by reference . Otherwise, the stored value is not even the value observed in the function.
Third, we must return by reference , putting an ampersand in a function declaration. You have already done this, except for this code:
$ref =& self::$global_registry[$key]; // redundant line return $ref;
Same as this code:
return self::$global_registry[$key];
Since in the line public static function &get we have already announced that the return value is a reference.
- And finally, we need to assign a return link to the link that you also made:
$test2 =& Registry::Get("config");
As you can see, the whole chain should be a link. If any step is not taken by the referee, this will not work.
source share