【www.gdgbn.com--ruby】

作者:老王

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];
  &

本文来源:http://www.gdgbn.com/jiaocheng/12364/