IMB
IMB

Reputation: 15889

Are there any valid use case for using public variables in PHP OOP?

Variable encapsulation, Set/Get methods are best practices but why do we have a chance to declare a variable public if it's not meant to be used anyway? Would it have been better if variables were always private by default with no chance of making them public since all of the tutorials I read says they should be encapsulated with set/get methods? Is there any valid use case for public variables at least in PHP OOP?

Upvotes: 7

Views: 206

Answers (3)

aifarfa
aifarfa

Reputation: 3939

let's see.. this's a real world Email API class from CakePHP EmailComponent. to use this class you only need to "set" some property then just send()

$this->Email->to = '[email protected]';
$this->Email->from = '[email protected]';
$this->Email->title = 'xxx';
$this->Email->msg = 'blabla..';
$this->Email->send();

in fact there is a lot of private properties and function inside this class but it's private.

Class has (single) responsibility to do something. Encapsulation is to publish only what people use to do that thing and keep technical/infrastructure inside as private.

Upvotes: -1

KingCrunch
KingCrunch

Reputation: 131881

In fact it's just the other way round: Theoretically getters/setters are wrong. The properties defines the state of an object, where the methods defines the behaviour. Getters/Setters only intercept the read and write access to properties, but they break the semantic meaning completely: Now reading the status of an object is a behaviour of the object.

To make properties to look like properties again there is a RFC on the road :) https://wiki.php.net/rfc/propertygetsetsyntax

Upvotes: 8

hakre
hakre

Reputation: 197767

Set/Get methods are best practices but why do we have a chance to declare a variable public if it's not meant to be used anyway?

Best practices and not meant to be used is not the same. A language needs to offer different tools for different use-cases and should be consistent.

PHP objects always supported public members and when differentiated visibility was introduced, for backwards compatible reasons public members are very useful.

Would it have been better if variables were always private by default with no chance of making them public since all of the tutorials I read says they should be encapsulated with set/get methods?

That question can not be specifically answered, it's too subjective and there are too many different use-cases that would result in a different answers.

Is there any valid use case for public variables at least in PHP OOP?

Start with backwards compatiblity. If you can not refactor your code but would need to rewrite it completely all the time, this would be very expensive.

Upvotes: 1

Related Questions