对比Php和Ruby的getter/setter实现方式

作者:老王

Getter/Setter的用法在Java社区里很常见,比如说在Entity Bean或者DTO中,这东西有的时候很必要,有的时候则乏味得很。Php社区一般都是跟着Java社区的步伐匍匐前进,所以很多人在思想上继承了这样的做法。

先看看PHP中最一般的做法:

class Demo {
      private $name;
      private $age;

      public function getName() {
          return $this->name;
      }

      public function setName($name) {
          $this->name = $name;
      }

      public function getAge() {
          return $this->$age;
      }

      public function setAge($age) {
          $this->age = $age;
      }
}

当然,因为Php脚本语言的灵活性,借助__call这样的魔术方法,如果你的属性很多,我们可以写得更简便些:

class Demo {
      private $name;
      private $age;

      public function __call($name, $args) {
          if (preg_match('/^(get|set)(/w+)/', $name, $match)) {
              $firstChar = substr($match[2], 0, 1);
              $lastChars = substr($match[2], 1);
              $this->$attribute = strtolower($firstChar) . $lastChars;

              if ('get' == $match[1]) {
                  return $this->$attribute;
              } else {
                  $this->$attribute = $args[0];
              }
          }
      }

      public function getName() {
          return $this->name;
      }

      public function setName($name) {
          $this->name = $name;
      }
}

再来看看Ruby的做法:

class Demo
    attr_accessor :name, :age

    def name
      @name
    end

    def name=(name)
      @name = name
    end
end

综上所述,在Php中,我们可以使用__call来拦截对方法的请求,进而完成大多数属性的getter/setter操作,对于有特殊要求的属性,我们可以自定义方法来做(如getName, setName)。在Ruby中,是使用attr_accessor(或者 attr)来控制对属性的读写的,更细致的还有(attr_reader, attr_writer),对于有特殊要求的属性,可以通过定义相应的读写方法来做(如def name和def name=(name))。

注意:attr和attr_accessor不同,attr有一个writable参数,表示是否可写,缺省是false。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值