How do getters and setters work?

后端 未结 6 1980
北恋
北恋 2020-11-21 07:43

I\'m from the php world. Could you explain what getters and setters are and could give you some examples?

6条回答
  •  梦谈多话
    2020-11-21 07:58

    1. The best getters / setters are smart.

    Here's a javascript example from mozilla:

    var o = { a:0 } // `o` is now a basic object
    
    Object.defineProperty(o, "b", { 
        get: function () { 
            return this.a + 1; 
        } 
    });
    
    console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
    

    I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.

    2. Getters / setters in php

    Example from sof

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

    citings:

    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
    • http://tweener.ivank.net/
    • Getter and Setter?

提交回复
热议问题