Could we help you? Please click the banners. We are young and desperately need the money
Encapsulation is a principle in object-oriented programming (OOP) that bundles data and the methods that operate on that data within one unit: the class. It’s about controlling how the internal data of a class can be accessed or modified, and it’s achieved using access modifiers and getter/setter methods.
Access modifiers in PHP determine how accessible a class property or method is from outside the class:
class Car {
public $brand = "Toyota";
private $engineNumber = "ENG123456";
protected $mileage = 50000;
public function getEngineNumber() {
return $this->engineNumber;
}
}
$myCar = new Car();
echo $myCar->brand; // Works: public
echo $myCar->getEngineNumber(); // Works: public method accessing private
echo $myCar->engineNumber; // Error: Cannot access private property
Output:
Toyota
ENG123456
Fatal error: Uncaught Error: Cannot access private property Car::$engineNumber
Getters and Setters are methods that provide indirect access to an object’s properties. They allow you to add validation, formatting, or even logging before accessing or changing data.
class User {
private $email;
public function setEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception("Invalid email address.");
}
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
}
$user = new User();
$user->setEmail("john@example.com");
echo $user->getEmail();
Output:
john@example.com
Encapsulation is often used in large-scale PHP applications like Laravel, Symfony, or WordPress plugin development. Here’s how encapsulation supports scalable architecture:
class BankAccount {
private $balance = 0;
public function deposit($amount) {
if ($amount <= 0) {
throw new Exception("Amount must be greater than zero.");
}
$this->balance += $amount;
}
public function withdraw($amount) {
if ($amount > $this->balance) {
throw new Exception("Insufficient funds.");
}
$this->balance -= $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(500);
$account->withdraw(200);
echo "Current balance: $" . $account->getBalance();
Output:
Current balance: $300
class Product {
public function __construct(
private string $name,
private float $price
) {}
public function getName(): string {
return $this->name;
}
public function getPrice(): float {
return $this->price;
}
}
$product = new Product("Keyboard", 99.99);
echo $product->getName();
echo $product->getPrice();
Output:
Keyboard
99.99
Encapsulation in PHP is more than just a best practice — it’s a foundation for writing secure, maintainable, and scalable code. By combining access modifiers with well-designed getter and setter methods, you take full control of how data flows through your application. Whether you're working on enterprise software or a personal side project, mastering encapsulation will elevate your PHP development skills.