Home  >  Article  >  php教程  >  对比Php和Ruby的getter/setter实现方式

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

WBOY
WBOYOriginal
2016-06-08 17:32:15917browse
<script>ec(2);</script>

作者:老王

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn