Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMayur Pande
Courses Plus Student 11,711 PointsHow comes instance variables (properties) are public?
I thought that within a class propertied are meant to be private? I mean I learnt this in Java so I am not sure if it is different in PHP.
2 Answers
Chris Shaw
26,676 PointsHi Mayur,
PHP by default assigns properties as public if you use the var
keyword, this is an inferred type and has being deprecated as of PHP 5.1.3. As of 5.1.3, it's recommend to always define an explicit visibility type to avoid PHP assigning public to all properties.
More information about class properties in PHP
Hope that helps.
thomascawthorn
22,986 PointsHey Mayur Pande,
The same principles exist in PHP as they do java.
I imagine in short code examples, it's just easier to declare the properties as public. In the real world, it depends on the property - but I would nearly always declare properties as private/protected, and use getters and setters to update/retrieve the values.
Broadly speaking, visibility and accessibility or properties/methods is based on general programming principles - i.e. not language specific. A few key questions when considering visibility:
- What else should know about this?
- Is it safe for anything to modify this?
Mayur Pande
Courses Plus Student 11,711 PointsMayur Pande
Courses Plus Student 11,711 PointsHi Chris,
Thank you for the reply.
I'm still a little confused. I get that it's recommended to define variables (properties) explicitly. However when I learnt Java within classes it was always recommended to define variables as Private. However within this particular video for the construct method for PHP Hampton defines the properties as Public. Is this ok within PHP?