吸气剂和吸气剂? [英] Getter and Setter?

查看:33
本文介绍了吸气剂和吸气剂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是 PHP 开发人员,所以我想知道在 PHP 中使用显式 getter/setter 是否更流行,以纯 OOP 风格,带有私有字段(我喜欢的方式):

I'm not a PHP developer, so I'm wondering if in PHP is more popular to use explicit getter/setters, in a pure OOP style, with private fields (the way I like):

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;
}

谢谢

推荐答案

您可以使用 php 魔术方法 __get__set.

You can use 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;
  }
}
?>

这篇关于吸气剂和吸气剂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆