Php __get 和 __set 魔术方法 - 为什么我们需要这些方法? [英] Php __get and __set magic methods - why do we need those here?
问题描述
此处的 Zend 快速入门指南 http://framework.zend.com/manual/en/learning.quickstart.create-model.html 我们可以看到:
On Zend Quick Start Guide here http://framework.zend.com/manual/en/learning.quickstart.create-model.html we can see:
class Application_Model_Guestbook
{
protected $_comment;
protected $_created;
protected $_email;
protected $_id;
public function __set($name, $value);
public function __get($name);
public function setComment($text);
public function getComment();
...
我通常在没有任何魔法方法的情况下创建我的 getter 和 setter.我在快速指南上看到过这个,我不明白为什么我们需要这个.
I normally create my getters and setters without any magic method. I've seen this on the quick guide, and I don't understand why may we need this.
有人可以帮我吗?
非常感谢
推荐答案
您(通常)从不直接调用 __set
或 __get
.$foo->bar
会在 bar
不可见且 时自动调用
存在.$foo->__get('bar')
__get
You (usually) never call __set
or __get
directly. $foo->bar
will call $foo->__get('bar')
automatically if bar
is not visible and __get
exists.
在您链接到的教程中,getter 和 setter 被设置为自动调用适当的单个 get/set 函数.所以 $foo->comment = 'bar'
会间接调用 $foo->setComment('bar')
.这没有必要……只是为了方便.
In the tutorial you've linked to, the getter and setter get set up to automatically call the appropriate individual get/set functions. So $foo->comment = 'bar'
will indirectly call $foo->setComment('bar')
. This isn't necessary... it's only a convenience.
在其他情况下,__get
可用于创建看起来像只读变量的内容.
In other cases, __get
can be useful to create what looks like a read-only variable.
这篇关于Php __get 和 __set 魔术方法 - 为什么我们需要这些方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!