Reputation: 791
I begun to learn PHP Classes & Methods and as a practice exercise I decided to create a Class called Bank Account and trying to implement DisplayBalance(), Withdrawals() and Transaction() Methods.
Most of it works and I am able to display a balance as well as add and subtract 'money' from a account, but what I also want to do is when money is withdrawn beyond the initial balance to remove a balance echo message and replace it with a i.e echo'NO more money'.
At the moment the error message pops up but the balance is also shown. Can someone point me in a right direction please quiet frustrating as i begun to enjoy my experience with classes and methods!
My code:
<?php
class BankAccount{
public $balance = 10.5;
public function DisplayBalance(){
if(($this->balance)<0){
return false;
}else{
return 'Balance: '.$this->balance.'</br>';
}
}
public function Withdraw($amount){
if (($this->balance)<$amount){
echo 'Not Enough Founds: '.'</br>';
}else{
$this->balance=$this->balance - $amount;
}
}
public function Transaction($trans){
$this->balance=$this->balance + $trans;
}
}
$alex = new BankAccount;
$alex->Withdraw(12);
echo $alex->DisplayBalance();
$abdul = new BankAccount;
$abdul->Transaction(10);
echo $abdul->DisplayBalance();
?>
Upvotes: 0
Views: 460
Reputation: 480
public function Withdraw($amount){
$this->balance=$this->balance - $amount;
}
public function DisplayBalance(){
if($this->balance < 0){
return 'Not Enough Funds: '.'</br>';
}else{
return 'Balance: '.$this->balance.'</br>';
}
}
or you can try this one
class BankAccount{
public $balance = 10.5;
public $error = false;
public function DisplayBalance(){
if($this->error){
$this->error = false;
return 'Not Enough Funds: '.'</br>';
}else{
return 'Balance: '.$this->balance.'</br>';
}
}
public function Withdraw($amount){
if (($this->balance)<$amount){
$this->error = true;
}else{
$this->balance=$this->balance - $amount;
}
}
}
$alex = new BankAccount;
$alex->Withdraw(12);
echo $alex->DisplayBalance();
Upvotes: 0
Reputation: 1454
You're doing withdraw(12) first, and this is what happens:
if (($this->balance)<$amount){
echo 'Not Enough Founds: '.'</br>';
And that's it, no substraction is executed. Then you do display():
public function DisplayBalance(){
if(($this->balance)<0){
return false;
}else{
return 'Balance: '.$this->balance.'</br>';
}
}
Well, $this->balance is still 10.5 as in previous function you've just echoed an error and haven't made any $this->balance - $arg. Try fixing it like this:
public function Withdraw($amount){
if (($this->balance)<$amount){
// $this->balance=0; you can zero your balance out
// $this->balance -= $amount; or just make it -1.5 so display() function would
// do its job
echo 'Not Enough Funds: '.'</br>';
}else{
$this->balance=$this->balance - $amount;
}
}
Upvotes: 2