Creating a bank_account Class

Nov 06, 2009 Author: Developer

To demonstrate the use of a class, lets create one to model a bank account.A bank account has certain information associated with it, such as itsaccount number, the PIN number needed to access it, and its balance.

This information could be stored in a class’s member variables.Here is the class declaration with only the member variables declared:

class bank_account
{
var $Number, // (string) Account Number (xxx-xxxx-xxxx)
$PIN, // (int) PIN Number (xxxx)
$Balance; // (double) Balance (xxxx.xx)}
These functions will be changing the value of certain member variableswithin the class. To do so, we must use the $this object. THE $this OBJECT$this is used to access the contents of an object from within its own memberfunctions. To modify a variable from within a member function definition,you use $this->variable_name, where variable_name is one of theclass’s member variables. For example, bank_account Class could be used to create a rudimentary checkbook-balancing program, as follows:
<?php
// MAIN PROGRAM
$in = $HTTP_POST_VARS;
switch($in[‘action’])
{
default:
showForm();
break;
case ‘Deposit’:
$objAccount = new bank_account;
$objAccount->Balance = $in[‘previous-balance’];
$objAccount->Deposit($in[‘amount’]);
showForm($objAccount->Balance);
break;
case ‘Withdraw’:
$objAccount = new bank_account;
$objAccount->Balance = $in[‘previous-balance’];
$objAccount->Withdraw($in[‘amount’]);
showForm($objAccount->Balance);
break;
}
// FUNCTION DEFINITIONS
function showForm($dblBalance = 0)
// PRE: none
// PST: An HTML form is displayed to allow input into the program
{
?><html><head><title>Pela PHP Tutorial</title></head>
<body bgcolor=”white”>
<form action=”<?= $GLOBALS[‘PHP_SELF’] ?>” method=”POST”>
<!-- hidden input to track balance from one submission to the next -->
<input type=”hidden” name=”previous-balance” value=”<?= $dblBalance ?>”>
<b>Account Balancing Program</b><br>
Previous Balance: <?= $dblBalance ?><br>
Amount: <input type=”text” name=”amount”><br>
<input type=”submit” name=”action” value=”Withdraw”><br>
<input type=”submit” name=”action” value=”Deposit”>
</form>
</body>
</html>
<?php
}
 // end of showForm()
// CLASS DEFINITIONS
class bank_account
{
var $Number, // (string) Account Number (xxx-xxxx-xxxx)
$PIN, // (int) PIN Number (xxxx)$
Balance; // (double) Balance (xxxx.xx)
function Deposit($dblAmount)
{
$this->Balance += $dblAmount;
}
function Withdraw($dblAmount)
{
$this->Balance -= $dblAmount;
}
}
?>
Like all other variables in PHP, object variables are not persistent; that is, each time PHP runs, the object that exists has to be re-created. It is not the same object everytime the user clicks a Deposit or Withdraw button. This is why the previous-balance hidden field is included in the form.

As you can see, the first time the program runs (when the user first visitsit), no action is defined. In response, the program simply returns the form.


views 6688
  1. Add New Comment