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 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效