re: PHP Typed Properties: Think Twice. VIEW POST

re: Both of these examples are flawed. First, you shouldn't be using public fields. Full stop. It breaks encapsulation, leaks implementation details o...

"First, you shouldn't be using public fields."

It is cargo-cult that every OOP programmer has followed since eons.

For example.

public $field;


private $field;
public setField($value) {$this->field=$value;}
public getField() {return $this->field;}

What it's the gaining of private versus public: nothing but more code!.


I second that!

Context is key here. There are objects in our daily life that are just a way to organise data. DTO's, entities and such. The integrity of those objects should be made sure from the outside anyway.

And then there are objects whose inner state is critical. It's objects where you might only want to expose properties via constructor and getters to control the state.

However, both types don't really justify hiding protected or private properties behind getters and setter that don't do anything else but to expose said properties as if they were public in the first place.


no, you've gained the option of doing anything else at the point of get and set - you can change your implementation - you can refactor your field into something different and maintain your existing interface. a public field is just that, once its there you can never remove it.

In my experience, to hide logic in the getter or setter is dangerous because nobody would expect something there (unless it is a visual object such a button or textbox). So, finally, the getter and setters are a dummy.

Proof, C# has properties, they are a dummy but they are short & easy to write.

int MyProp {set; get;}

code of conduct - report abuse