0
0
PhpConceptBeginner · 3 min read

What is Encapsulation in PHP: Simple Explanation and Example

In PHP, encapsulation is a way to keep the internal details of a class hidden from the outside world by using private or protected properties and methods. It helps control access to data and protects it from unwanted changes, making your code safer and easier to manage.
⚙️

How It Works

Think of encapsulation like a capsule that holds medicine inside. You only get to see the outside and take the medicine as intended, but you don't see or change what's inside the capsule. In PHP, a class can hide its data (properties) and only allow access through special methods called getters and setters.

This means you control how the data is read or changed, preventing accidental or harmful changes. It keeps your code organized and safe, just like locking your valuables in a safe and giving keys only to trusted people.

💻

Example

This example shows a class with a private property and public methods to get and set its value. The private property cannot be accessed directly from outside the class.

php
<?php
class User {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

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

    public function setName(string $name): void {
        if (strlen($name) > 0) {
            $this->name = $name;
        }
    }
}

$user = new User("Alice");
echo $user->getName(); // Outputs: Alice

$user->setName("Bob");
echo "\n" . $user->getName(); // Outputs: Bob

// The following line would cause an error because name is private
// echo $user->name;
Output
Alice Bob
🎯

When to Use

Use encapsulation whenever you want to protect important data inside your classes from being changed directly. It is especially useful in large projects where many parts of the code interact, helping avoid bugs caused by unexpected changes.

For example, if you have a bank account class, you want to control how the balance changes to prevent errors or fraud. Encapsulation lets you add checks inside setter methods to keep data valid and safe.

Key Points

  • Encapsulation hides class details using private or protected keywords.
  • Access to data is controlled through public getter and setter methods.
  • It protects data from accidental or unauthorized changes.
  • Encapsulation improves code maintainability and security.

Key Takeaways

Encapsulation hides class data to protect it from direct access.
Use private or protected properties with public getters and setters.
It helps keep your code safe, organized, and easier to maintain.
Encapsulation is essential for controlling how data changes in your programs.