Encapsulation (computer programming): Difference between revisions

Content deleted Content added
No edit summary
Sameg14 (talk | contribs)
No edit summary
Line 61:
 
<source lang="php">
<?php
class person {
class Account
var $name;
{
public $height;
/**
protected $social_insurance;
* How much money is currently in the account
private $pinn_number;
* @var float
*/
function __construct($persons_name) {
private $accountBalance;
$this->name = $persons_name;
}
function set_name($new_name) {
$this->name = $new_name;
}
 
/**
function get_name() {
* @param float $currentAccountBalance Initialize account to this dollar amount
return $this->name;
*/
}
public function __construct($currentAccountBalance)
{
}
$this->accountBalance = $currentAccountBalance;
}
 
/**
* Add money to account
* @param float $money Dollars to add to balance
* @return void
*/
public function add($money)
{
$this->accountBalance += $money;
}
 
/**
* Remove money from account
* @param float $money Dollars to subtract from balance
* @throws Exception
* @return void
*/
public function withdraw($money)
{
if($this->accountBalance < $money){
throw new Exception('Cannot withdraw $'.$money.' from account as it contains $'.$this->accountBalance);
}
$this->accountBalance -= $money;
}
 
/**
* Get current account balance, that takes all additions and subtractions into consideration.
*
* @return float
*/
public function getAccountBalance()
{
return $this->nameaccountBalance;
}
}
 
// Create a new object from the Account class with a starting balance of $500.00
$myAccount = new Account(500.00);
 
// We have clearly defined methods for adding and subtracting money from the Account
// If we didn't have a method for withdraw(), nothing would prevent us from withdrawing more money than was available in the account
$myAccount->add(10.24);
$myAccount->withdraw(4.45);
 
// Get the current balance
$accountBalance = $myAccount->getAccountBalance();
echo 'My Account Balance: $' . $accountBalance; // 505.79
 
// Our code forbids us from withdrawing more than we have
$myAccount->withdraw(600.00); // Exception Message: Cannot withdraw $600 from account as it contains $505.79
</source>