php
  1. php-encapsulation

PHP Encapsulation

Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP) that refers to the practice of protecting the internal state of an object from other objects. It allows us to keep the class data members or variables private from other classes.

Syntax of encapsulation in OOP using PHP:

class ClassName {
   private $variableName;
   // Methods
   private function functionName() {
      // Method code
   }
}

Example of encapsulation in PHP:

class BankAccount {
   private $balance;

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

   public function getBalance() {
      return $this->balance;
   }

   public function deposit($amount) {
      $this->balance += $amount;
   }

   public function withdraw($amount) {
      if ($amount > $this->balance) {
         return "Insufficient balance.";
      } else {
         $this->balance -= $amount;
         return $amount . " withdrawn successfully.";
      }
   }
}

Output:

$account = new BankAccount(1000);
echo "Current balance: " . $account->getBalance() . "\n"; // Current balance: 1000
$account->deposit(500);
echo "After deposit: " . $account->getBalance() . "\n"; // After deposit: 1500
echo $account->withdraw(2000); // Insufficient balance.
echo "After withdrawal: " . $account->getBalance() . "\n"; // After withdrawal: 1500

Explanation: In the above example, we have defined a BankAccount class and its methods. The $balance variable is set to private, thus encapsulated. The getBalance method is public and can be accessed by other classes to get the account balance. The deposit and withdraw methods are used to add and withdraw money from the account only if the requested amount is not more than the account balance.

Use: Encapsulation is used to prevent access to internal data from outside the class, reduce software complexity and increase flexibility. It facilitates code reusability and helps in avoiding errors and conflicts with namespaces.

Important Points:

  • Encapsulation is one of the four fundamental concepts of OOP, along with inheritance, polymorphism, and abstraction.
  • Private variables and methods are inaccessible from outside the class.
  • Getters and setters are used to access and modify private data members respectively.
  • Encapsulation ensures data integrity and security.

Summary: In PHP, encapsulation is a mechanism of OOP that aims to keep the state and behavior of an object hidden from the outside world. By defining private properties and methods in a class, encapsulation helps in maintaining the integrity of data and allows a developer to control access to the class members.

Published on: