Encapsulation is one fundamental concept of object-oriented programming. It refers to the bundling of data with the methods that operate on that data. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties’ direct access to them.
That’s it, the object properties (and some of its methods) should be private
(or, sometimes, protected
)
and not public
.
Let’s see an example:
1 | class User { |
The code above uses the keyword “class” and because of that, according to many developers, it is object-oriented code. In fact, it is pure procedural code.
Let’s put it side-by-side against the same code written in C, a procedural language that does not provide any object-oriented feature.
1 | /* "Object-oriented" PHP code */ | /* Procedural C code */ |
Letting apart the inherent differences due to syntax, can you spot any difference of style in the two fragments above? I cannot.
It is the same code, procedural beyond a shadow of a doubt.
Case closed.
Addendum: There are cases when public properties are the way to go. I’ll write about them in a future post.