How can the concept of encapsulation be better implemented in PHP classes to ensure data integrity and security?
To better implement encapsulation in PHP classes for data integrity and security, we can use access modifiers like private and protected to restrict direct access to class properties from outside the class. This ensures that data can only be accessed or modified through designated getter and setter methods, allowing for better control over how data is manipulated.
class User {
private $username;
public function setUsername($username) {
// Add validation logic here if needed
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
}
$user = new User();
$user->setUsername("john_doe");
echo $user->getUsername(); // Output: john_doe