Php __get 和 __set 魔术方法 - 为什么我们需要这些方法? [英] Php __get and __set magic methods - why do we need those here?

查看:41
本文介绍了Php __get 和 __set 魔术方法 - 为什么我们需要这些方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆