DEV Community


Discussion on: Object Oriented Programming

aleksikauppila profile image
Aleksi Kauppila

Wonderful that OOP concepts are gaining popularity within PHP devs. Most of the time i see a lot of procedural code which is no wonder as even popular frameworks prefer procedural style.

I do feel that there's a lot of misunderstanding about inheritance. It's wonderful for subtyping. One thing mentioned many times is that inheritance breaks encapsulation. I don't see why it has to be like that. Using private visibility modifier in parent classes will restrict access from child classes and force them to use the same public api as everybody else. No problem right?

However regarding encapsulation: i think using getters and setters (especially the way presented in your example) expose needlessly internals of the object. Particularly setting shouldn't happen at all. There should be a clear business operation that changes the state of the object in a controlled manner. Getting and setting are inherently procedural: asking what objects know, doing operations based on that, changing data of other objects. You did mention tell don't ask.


if ($article->getStatus() !== Article::STATUS_PUBLISHED) {
    $article->setPublishedDate(new DateTime());


if (!$article->isPublished()) {
    $article->publish(new DateTime());

In the procedural example there's a need to know about implementation details of the class which effectively breaks encapsulation. In OOP example were just concerned about article's public API.