Sobes.tech
Junior

What is encapsulation in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation is the combination of data (properties) and methods that work with this data into a single entity (object or class), as well as hiding the internal implementation from the outside world. This allows controlling access to the data and modifying the internal structure of the class without affecting the rest of the code.

Main aspects of encapsulation:

  1. Data hiding: Direct access to the internal data of the object is restricted. Access is provided through public methods - getters (to retrieve data) and setters (to modify data).
  2. Invariants compliance: Class methods can contain logic to verify the correctness of data during setting, ensuring that the object remains in a valid state.

Example:

<?php
class User {
    private string $name; // Property is hidden
    private int $age;    // Property is hidden

    public function __construct(string $name, int $age) {
        $this->setName($name);
        $this->setAge($age);
    }

    // Getter for name
    public function getName(): string {
        return $this->name;
    }

    // Setter for name with possible validation
    public function setName(string $name): void {
        // Validation for name can be added if necessary
        $this->name = $name;
    }

    // Getter for age
    public function getAge(): int {
        return $this->age;
    }

    // Setter for age with validation
    public function setAge(int $age): void {
        if ($age < 0) {
            throw new InvalidArgumentException("Age cannot be less than zero.");
        }
        $this->age = $age;
    }

    // Method using internal data
    public function introduce(): string {
        return "My name is " . $this->name . " and I am " . $this->age . " years old.";
    }
}

// Using the class
$user = new User("Ivan", 30);
echo $user->introduce(); // Output: My name is Ivan and I am 30 years old.

// Attempting direct access to a private property will cause an error:
// $user->age = -5; // Fatal error: Uncaught Error: Cannot access private property User::$age

// Using setter with validation
try {
    $user->setAge(-5);
} catch (InvalidArgumentException $e) {
    echo "\nError: " . $e->getMessage(); // Output: Error: Age cannot be less than zero.
}

Advantages of encapsulation:

  • Access control: Defines how external objects can interact with the class data.
  • Flexibility: Allows changing the internal implementation of the class without the need to change the external code that uses it.
  • Improved maintainability: Simplifies debugging and modification, as changes are confined within the class.
  • Data protection: Prevents incorrect modification of the object's state.