PHP - Making Your Classes Self-Contained with Encapsulation

Introduction

A class's internal data should be protected from being directly manipulated from outside.

The details of the class's implementation - such as how it stores values or manipulates data - should be hidden from the outside world.

All internal properties of a class should be declared private.

If outside code needs to access those variables, it should be done through a public method.

You can validate the changes requested by the outside code and accept or reject them.

Demo

<?php
class Account {/*w  w  w  .j av a 2s .  c o m*/
           private $_totalBalance = 0;

           public function makeDeposit($amount) {
             $this->_totalBalance += $amount;
           }

           public function makeWithdrawal($amount) {
             if ($amount  <  $this->_totalBalance) {
               $this->_totalBalance -= $amount;
             } else {
               die("Insufficient funds \n");
             }
           }
           public function getTotalBalance() {
             return $this->_totalBalance;
           }
}

$a = new Account;
$a->makeDeposit(500);
$a->makeWithdrawal(100);
echo $a->getTotalBalance()."\n";  // Displays"400";
$a->makeWithdrawal(1000);  // Displays"Insufficient funds"
?>

Result

Here, because the variable storing the account balance is private, it can't be manipulated directly.

By encapsulating internal data and method implementations, an object-oriented application can

  • protect and control access to its data and
  • hide the details of implementation,
  • make the application more flexible and more stable.

Related Topic