![]() |
VOOZH | about |
Private properties are variables that cannot be accessed directly from outside the class in which they are defined. They support encapsulation, a key principle of object-oriented programming (OOP), by keeping internal data protected and manageable.
To illustrate private properties, let's consider a simple User class where each user has a unique ID. We want to ensure that this ID cannot be changed directly from outside the class.
Here's how you might define the User class with a public property:
In the example above, the id property is public, meaning it can be accessed and modified directly from outside the class. This could lead to potential issues if the ID is inadvertently changed.
To convert this into a private property, you can use the new private field syntax by adding a # before the property name:
While private properties add a valuable layer of protection, they come with some limitations: