What are the benefits of using getter and setter methods in PHP classes?
Using getter and setter methods in PHP classes helps to enforce encapsulation by controlling access to class properties. This allows for better data validation and manipulation, as well as providing a clear interface for interacting with the class properties.
class User {
private $username;
public function setUsername($username) {
// Perform validation or manipulation here
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
}
$user = new User();
$user->setUsername("john_doe");
echo $user->getUsername(); // Output: john_doe