PHP has _get and _set functions built in. Is it better to write my own get and set functions for each variable or use the built in functions with a ton of if else if? What are the pros and cons of each method?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
__getand__setare magic methods that should usually be used to solve difficult problems rather than to be used as a design basis.For instance, I found myself on a project where I had to analyze a site that used OOP with deep inheritance (> 2) and one of the important base classes had a public property called
name. However, it also had getters and setters (getName,setName) that accessed that property for the mere purpose of getting and setting it. Many classes calledgetNameand just as many accessed thenameproperty directly! Not great design.The magic methods allowed me to solve the problem by renaming the property to
_nameand making it private, forcing all requests to the property through the getters and setters.This being said, there’s no need for getters and setters if you’re just treating a property like a variable. In that case, just make the property public!
In your case, since there is validating/sanitizing going on, you should employ getters and setters and code them directly as methods (rather than unnecessarily incurring the overhead from the magic methods).