How can the use of getter and setter methods in PHP classes affect the accessibility of attributes within objects?
Using getter and setter methods in PHP classes can help control the accessibility of attributes within objects by allowing you to enforce validation or logic before setting or getting a value. This can prevent direct access to object properties and ensure that data is handled in a consistent manner.
class User {
private $username;
public function setUsername($username) {
// Perform validation or logic before setting the username
$this->username = $username;
}
public function getUsername() {
// Perform any additional logic before returning the username
return $this->username;
}
}
$user = new User();
$user->setUsername("john_doe");
echo $user->getUsername();