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 trial

PHP Object-Oriented PHP Basics Building the Recipe Adding Getters and Setters

Mohammed Jammeh
Mohammed Jammeh
37,463 Points

Why use 'Getters' and 'Setters' to access private properties in PHP objects?

Why does one have to add 'getters' and 'setters' to access private properties in PHP objects. I do understand that it allows one to access private properties outside the class. However, why use 'Getters' and 'Setters' instead of just making the properties public?

Sorry, if my question's confusing, I'm new to this stuff.

Thank you.

1 Answer

Jason Cook
Jason Cook
11,403 Points

That's a good question. Getters and setters have advantages and disadvantages to consider, however to answer your question, I'll focus on advantages.

For example, when using a setter, the setter function could perform checks on the provided value, to determine if it's in range and/or a valid setting. If the value provided is erroneous, you could either continue using the last known good value (the one already set), or even go into a fail over condition or safe state, if such input is vital for proper or safe operation.

In the case of getters, you might want to trigger some type of action (such as logging) when a value is retrieved.

There are other considerations, of course, but this is what came to my mind at the moment. You might also want to look at magic methods, as a third option, just to give yourself an understanding of alternative options.

You might consider the following article, if you want more details on the advantages and disadvantages of each option, and which cases you might use one or another method.

http://russellscottwalker.blogspot.com/2013/09/public-properties-getters-and-setters.html

I hope this helps! Happy coding! :-)

Mohammed Jammeh
Mohammed Jammeh
37,463 Points

Oh okay, I get it now. I found it hard wrap my head around their usefulness but I do understand it now. Thanks Jason, I really appreciate it.