Getter&Setter也适合在课堂上使用? [关闭]

It is a bad way of programming, when i get access to my private/protected class members directly in the class via my getter/setter methods?

Alternative #1

<?php

class A {
    private $myVariable;

    public function getMyVariable() {
        return $this->myVariable;
    }

    public function doSomething() {
        $variable = $this->getMyVariable();
    }
}

?>

Alternative #2

<?php

class A {
    private $myVariable;

    public function doSomething() {
        $variable = $this->myVariable;
    }
}
?>

Which way do you prefer? I think the first solution is more readable in constrast to the second one. Please let me hear your opinions.

Thanks in advance.

Since you are determined this is not a duplicate, I will copy the points from this response relevant to this case:

  • Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
  • Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
  • Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
  • Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.

Maybe you should think in another way: Why do we need getter/setter? They abstract direct access to a field. Even if the Getter does nothing other than setting a value, it can protect you later on. Changing a field to a Getter later is a breaking change, especially in PHP IDEs (badumm). So I think whenever you want to protect a field to prevent vulnerable/buggy code, use getter/setter.