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?
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,$varNameor 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
issetand makes your code more concise and robust.