What are getters and setters and why are they important?



What are getters and setters and why are they important?..

Answer / Brijesh Kumar Gautam

Getters (accessor methods) and setters (mutator methods) are used in object-oriented programming to control access to an object's private properties. They provide a way to encapsulate data and ensure that the data is valid before it is modified or accessed. This helps maintain the integrity of the data and makes the code more robust. Here's an example of how to create getters and setters in PHP:n```phpnclass Employee {n private $name;n private $salary;n public function __construct($name, $salary) {n $this->name = $name;n $this->salary = $salary;n }n public function getName() {n return $this->name;n }n public function setName($name) {n if (is_string($name)) {n $this->name = $name;n } else {n throw new Exception('Invalid name');n }n }n public function getSalary() {n return $this->salary;n }n public function setSalary($salary) {n if ($salary > 0) {n $this->salary = $salary;n } else {n throw new Exception('Invalid salary');n }n }n}n$employee = new Employee('John Doe', 50000);necho $employee->getName(); // Output: John Doen```

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More PHP Interview Questions

Which functions are used to remove whitespaces from the string?

1 Answers  


How can I reverse sort an array keeping the correlation between the index and value?

2 Answers   Rushmore Consultancy,


What is put method in php?

1 Answers  


How to track user logged out or not? When user is idle?

1 Answers  


Is empty in php?

1 Answers  


Tell me how is it possible to propagate a session id?

1 Answers  


How arrays are passed through arguments?

1 Answers  


What is difference between include and include_once in php?

1 Answers  


What is the difference between == and === in php?

1 Answers  


Why shouldn't I use mysql_* functions in php?

1 Answers  


1. Create student database. 2. First page should display the students available in the database. There should be add, edit and delete buttons. 3. There should be option to search students by name, code, date of joining, department or combination of these. 4. Should have an add/edit screen. Add and Edit should be handled in the same page. 5. Delete should ask for confirmation before deleting the actual record. 6. Validation should be done in JavaScript as well as php.

0 Answers   Zonex,


Explain what does the unset() function means?

1 Answers  


Categories