0

What's the point of using getters and setters if they will always stay default/empty?

What i mean by default/empty getter and setter:

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

public function __set($propertyName, $value)
{
    $this->$propertyName = $value;
}
Jo Smo
  • 6,923
  • 9
  • 47
  • 67

2 Answers2

1

The link of @j08691 is very good to understand the theory behind getters and setters. The magic methods are great, but have many disatvantages.

  • Your IDE can auto-complete with documentation.
  • You can also validate the type of a data :

    pulic function getProduct(Product $product)

Michael Villeneuve
  • 3,933
  • 4
  • 26
  • 40
1

A lot of times you are right they are pointless if you never expect to use them, however the point of them is to ensure ensure that class properties are only set and returned using these, so even if your parameters are being set from within the class you should use them. That way you are guaranteed that there is only one single place they are interfaced. Why would you want to have a single place you ask? Well if you decided to change anything about the parameter, say limit the values that are stored in it or change how it is stored by using a database, you have the abstraction away from directly accessing it and one single place that would need to be changed, rather than searching through the whole class (and any classes that inherited from it), to find all places that used the parameter.

Does that make sense?

Lisa
  • 23
  • 4