一尘不染

Getter and Setter?

php

我不是PHP开发人员,所以我想知道在PHP中,使用纯OOP风格的显式getter / setters是否具有私有字段(我喜欢这样)是否更受欢迎:

class MyClass {
    private $firstField;
    private $secondField;

    public function getFirstField() {
        return $this->firstField;
    }
    public function setFirstField($x) {
        $this->firstField = $x;
    }
    public function getSecondField() {
        return $this->secondField;
    }
    public function setSecondField($x) {
        $this->secondField = $x;
    }
}

或只是公共领域:

class MyClass {
    public $firstField;
    public $secondField;
}

谢谢


阅读 271

收藏
2020-05-26

共1个答案

一尘不染

您可以使用php magic methods __get and __set.

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>
2020-05-26