Jnr PHP/Codeigniter Developer Question:
Download Questions PDF

Explain me what are getters and setters and why are they important?

Answer:

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter one is able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If a setter is not being used and the developer is just declaring the $userName variable by hand, you could end up with results as such: "kevin", "KEVIN", "KeViN", "", etc. With a setter, the developer can not only adjust the value, for example, ucfirst($userName), but can also handle situations where the data is not valid such as the example where "" is passed. The same applies to a getter – when the data is being returned, it can be modifyed the results to include strtoupper($userName) for proper formatting further up the chain.

This is important for any developer who is looking to enter a team-based / application development job to know. Getters and setters are often used when dealing with objects, especially ones that will end up in a database or other storage medium. Because PHP is commonly used to build web applications, developers will run across getters and setters in more advanced environments. They are extremely powerful yet not talked about very much. It is impressive if a developer shows that he/she knows what they are and how to use them early on.

Download Jnr PHP/Codeigniter Developer Interview Questions And Answers PDF

Previous QuestionNext Question
Do you know how can we get the IP address of the client?Do you know what PSR Standards do you follow? Why would you follow a PSR standard?