我开始学习PHP Classes&方法和练习练习我决定创建一个名为Bank Account的类,并尝试实现DisplayBalance(),Withdrawals()和Transaction()方法。
大部分都有效,我可以显示余额以及从帐户中添加和减去“钱”,但我还想做的是在超出初始余额时提取资金以删除余额回复消息并用一个即echo'NO更多的钱来代替它。
此时会弹出错误消息,但也会显示余额。当有人开始享受我的课程和方法经验时,有人能指出我正确的方向吗安静令人沮丧!
我的代码:
<?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();
?>
答案 0 :(得分:2)
你先退出(12),这就是:
if (($this->balance)<$amount){
echo 'Not Enough Founds: '.'</br>';
就是这样,没有执行减法。然后你做display():
public function DisplayBalance(){
if(($this->balance)<0){
return false;
}else{
return 'Balance: '.$this->balance.'</br>';
}
}
好吧,$ this-&gt;余额仍然是10.5,就像之前的函数一样,你刚刚回复了一个错误并没有做出任何$ this-&gt;余额 - $ arg。尝试修复它:
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;
}
}
答案 1 :(得分:0)
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>';
}
}
或者你可以尝试这个
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();