如何在类中为定义的字段使用PHP的__get()和__set()? [英] How do I use PHP's __get() and __set() for defined fields in my class?

查看:234
本文介绍了如何在类中为定义的字段使用PHP的__get()和__set()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经很好地阅读了有关重载的PHP规范,并且大多数示例似乎旨在简单地允许定义自定义字段(类似于stdClass).

但是在我的课程中定义的私有字段呢?应该如何检索/分配这些?我可以对可能的值进行切换,然后对某些值采取行动:

class A
{
    private $name;
    private $age;

    public function __get( $var )
    {
        switch ( $var )
        {
            case 'name':
                return $this->name;
                break;
            case 'age':
                return $this->age+10; // just to do something different ;)
                break;
            default:
                break;
        }
    }
}

这是最好的方法,还是还有另一种公认的最佳实践? (我不知道是否可以在一个类中循环使用类变量,但是这在大多数情况下都不适合,因为您不想返回所有内容.)

解决方案

这将有效地将它们公开,并且通常这不会给您带来任何好处,而只是使用公共属性(但是您要付出性能代价,并且必须编写更多代码,存在错误) ).

仅当您已有使用公共属性的代码并且突然需要使用getter/setter时才使用该属性(例如您使用age的示例).

如果在读取/写入属性时需要执行一些代码(例如,使其成为只读或从数据库中延迟获取),则应使用常规的getter/setter方法(getAge()/setAge()). /p>

I've had a good read of the PHP specs on overloading, and most of the examples appear to be intended to simply allow defining of custom fields (similar to stdClass).

But what about the private fields defined in my class? How should these be retrieved/assigned? I could do a switch on possible values and act on certain values:

class A
{
    private $name;
    private $age;

    public function __get( $var )
    {
        switch ( $var )
        {
            case 'name':
                return $this->name;
                break;
            case 'age':
                return $this->age+10; // just to do something different ;)
                break;
            default:
                break;
        }
    }
}

Is this the best method, or is there another generally accepted best practice? (I don't know if it's possible to loop class variables inside a class, but regardless that's not appropriate in most situations since you don't want to return everything.)

解决方案

This would effectively make them public, and usually this gains you nothing over simply using public properties (but you pay performance penalty and have to write more code, risk bugs).

Use that only if you have existing code that uses public property and you suddenly need getter/setter for it (like your example with age).

If you need to execute some code when property is read/written (e.g. make it read-only or lazily fetch from the database), then you should use normal getters/setters (getAge()/setAge()).

这篇关于如何在类中为定义的字段使用PHP的__get()和__set()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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