首页 > php代码 > 对比Php和Ruby的getter/setter实现方式

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

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


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

<?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。


本文链接:http://www.phprm.com/code/126fc361afcc391fa83877e6b148dfb1.html

收藏随意^^请保留教程地址.

标签:none

发表留言