doudang4857 2009-07-25 01:45
浏览 55
已采纳

如何在我的类中使用PHP的__get()和__set()来定义字段?

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.)

  • 写回答

3条回答 默认 最新

  • dongqian3198 2009-07-25 02:05
    关注

    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()).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容