Sobes.tech
Junior — Middle

Can you explain the principle of encapsulation in PHP and how it is implemented in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation in PHP is an object-oriented programming mechanism that allows hiding the internal implementation details of an object and providing access to them only through certain methods.

In PHP, encapsulation is implemented using access modifiers:

  • public — access is open to everyone.
  • protected — access only within the class and its descendants.
  • private — access only within the class itself.

Example:

class User {
    private $password; // hidden property

    public function setPassword($pass) {
        // you can add validation or hashing
        $this->password = password_hash($pass, PASSWORD_DEFAULT);
    }

    public function verifyPassword($pass) {
        return password_verify($pass, $this->password);
    }
}

$user = new User();
$user->setPassword('secret');
var_dump($user->verifyPassword('secret')); // true

Thus, encapsulation helps protect the object's data from direct access and modification, ensuring control through class methods.