Getter and Setter?

前端 未结 15 676
南方客
南方客 2020-11-22 16:47

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):



        
相关标签:
15条回答
  • 2020-11-22 17:52

    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;
      }
    }
    ?>
    
    0 讨论(0)
  • 2020-11-22 17:52

    Generally speaking, the first way is more popular overall because those with prior programming knowledge can easily transition to PHP and get work done in an object-oriented fashion. The first way is more universal. My advice would be to stick with what is tried and true across many languages. Then, when and if you use another language, you'll be ready to get something accomplished (instead of spending time reinventing the wheel).

    0 讨论(0)
  • 2020-11-22 17:53

    Well, PHP does have magic methods __get, __set, __isset & __unset, which is always a start. Alas proper (get it?) OO properties is more than magic methods. The main problem with PHP's implementation is that magic methods are called for all inaccessible properties. Which means you have to Repeat Yourself (eg. by calling property_exists()) in the magic methods when determining if name is actually a property of your object. And you can't really solve this general problem with a base class unless all your classes inherit from ie. ClassWithProperties, since PHP lacks multiple inheritance.

    In contrast, Python new style classes gives you property(), which lets you explicitly define all your properties. C# has special syntax.

    http://en.wikipedia.org/wiki/Property_(programming)

    0 讨论(0)
提交回复
热议问题