Vael Victus
Vael Victus

Reputation: 4122

What's the purpose of stating public encapsulation for PHP OOP?

I'm dipping my toe into PHP's object-oriented side and I've been wondering about public encapsulation. I understand the purpose of private and protected encapsulation, but when it comes to public, why state it?

So for example, I have public $name;

But if I can just set $this->name = 'whatever', then whycome "public $varname" exists?

Upvotes: 0

Views: 192

Answers (1)

deceze
deceze

Reputation: 522372

Because it's always better to explicitly specify the properties of a class. Yes, you could just set them dynamically in a method when needed, but it makes it that much harder when you're trying to remember whether it was supposed to be $varname, $var_name, $varName or whether you have already "declared" the property at all.

It also makes sure the property exists when you're trying to work with it, which saves you calls to isset and makes your code more concise and robust.

Upvotes: 5

Related Questions