Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasoning Behind PHP5 Protected Variables

Tags:

php

protected

Can you explain what the reasoning would be on why I would want to use "protected" versus "public" or "private" on some class variables and methods in PHP5? I've just yet to find a case where I thought I needed "protected", and have either opted for "public" or "private" based on the intent. Even when working in teams, I have still yet to find a case (based on my knowledge thus far) of why "protected" is necessary for class variables and methods.

like image 484
Volomike Avatar asked Mar 22 '11 20:03

Volomike


1 Answers

For instance, the Flourish library's fDate class provides a lot of functionality but not everything I need. So I extended w/ my own class.

I soon found out that its core internal variable, fDate::$date (time in seconds since 1970), was a private property. This made it impossible for me to access it in my subclass ThriveDate. Once the maintainer of Flourish changed it to a protected property, I was able to use it and thus adequately extend fDate.

Since you never know who might need to extend your class, and by how much, in the future, it's always best to make every internal property protected, unless there are great reasons for the property to never be modified by subclasses.

TL;DR: Private properties should be as rare as public properties: e.g. used almost never.

like image 173
Theodore R. Smith Avatar answered Oct 07 '22 03:10

Theodore R. Smith