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 trialAlex Rendon
7,498 PointsWhat is the purpose to make a property or a method private or protected?
Why not set everything public?
3 Answers
Sergey Podgornyy
20,660 PointsClass members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited classes. Members declared as private may only be accessed by the class that defines the member.
jlampstack
23,932 PointsTo filter, format, protect and sanitize data so users can not modify them directly through the object. This can be dangerous against malicious attacks.
Lets say you have an <input> field for Name. Typically the user would enter their name, such as Alex. But without protecting it they can enter code into the field such as an HTML string when submitting the form. They can enter something like <h1>Alex</h1> it would be interpreted.
Submitting your name in an <h1> element is a silly example, but imagine if an attacker entered more malicious code. This can be harmful. By filtering the input with a function such as FILTER_SANITIZE_SPECIAL_CHARS the <h1> tag or anyother tag would be read as plain text instead of an element.
You may also want to format the text so the first letter of the name is always uppercase, limit the amount of characters a user can enter, etc. etc.
These are just a few examples.
Tibor Katai
2,102 PointsThanks Sergey!
Sergey Podgornyy
20,660 PointsYou are welcome
Tibor Katai
2,102 PointsTibor Katai
2,102 PointsThe public,private, protected i understand the theory. But why not set everything public? Why private,protected declaration is a better choose in the application? What is the purpose to make private, protected data?
Sergey Podgornyy
20,660 PointsSergey Podgornyy
20,660 PointsBecause sometimes you need to encapsulate data (More detailed)
Some of attributes in class should be available only for cooperation inside the class, so that noone can get access to them outside the class