问题描述
我已经在网络周围的几个地方,甚至在堆栈溢出上找到了代码,但是我无法将头缠住.我知道它的作用,但是即使在示例中,我也不知道它是如何做到的.基本上是存储值,但我不知道如何为注册表添加值.有人可以尝试解释该代码的工作原理,无论我如何设置和从中检索值吗?
class Registry { private $vars = array(); public function __set($key, $val) { $this->vars[$key] = $val; } public function __get($key) { return $this->vars[$key]; } }
推荐答案
它正在使用php hacked on 属性过载添加条目并从私有$vars数组中检索条目.
要添加属性,您将使用...
$registry = new Registry; $registry->foo = "foo";
在内部,这将通过魔术__set methot.
检索一个值...
$foo = $registry->foo;
在内部,这将通过魔术__get方法从$vars数组中检索foo.
__get方法应该真正检查不存在的条目并处理此类内容. IS代码将触发未定义索引的E_NOTICE错误.
更好的版本可能是
public function __get($key) { if (array_key_exists($key, $this->vars)) { return $this->vars[$key]; } // key does not exist, either return a default return null; // or throw an exception throw new OutOfBoundsException($key); }
其他推荐答案
基本上,您会做...
$Registry = new Registry(); $Registry->a = 'a'; //Woo I'm using __set echo $Registry->a; //Wooo! I'm using __get
所以在这里,我正在使用__set($a, 'This value is not visible to the scope or nonexistent') 另外,我正在使用__get($a);
希望这有所帮助!
问题描述
I've found the piece of code below in several places around the web and even here on Stack Overflow, but I just can't wrap my head around it. I know what it does, but I don't know how it does it even with the examples. Basically it's storing values, but I don't know how I add values to the registry. Can someone please try to explain how this code works, both how I set and retrieve values from it?
class Registry { private $vars = array(); public function __set($key, $val) { $this->vars[$key] = $val; } public function __get($key) { return $this->vars[$key]; } }
推荐答案
It's using PHP's hacked on property overloading to add entries to and retrieve entries from the private $vars array.
To add a property, you would use...
$registry = new Registry; $registry->foo = "foo";
Internally, this would add a foo key to the $vars array with string value "foo" via the magic __set method.
To retrieve a value...
$foo = $registry->foo;
Internally, this would retrieve the foo entry from the $vars array via the magic __get method.
The __get method should really be checking for non-existent entries and handle such things. The code as-is will trigger an E_NOTICE error for an undefined index.
A better version might be
public function __get($key) { if (array_key_exists($key, $this->vars)) { return $this->vars[$key]; } // key does not exist, either return a default return null; // or throw an exception throw new OutOfBoundsException($key); }
其他推荐答案
You might want to check out PHP.NET - Overloading
Basically, you would do...
$Registry = new Registry(); $Registry->a = 'a'; //Woo I'm using __set echo $Registry->a; //Wooo! I'm using __get
So here, I'm using __set($a, 'This value is not visible to the scope or nonexistent') Also, I'm using __get($a);
Hope this helped!