2013-11-29 2 views
0

PHP 클래스 &을 배우기 시작했습니다. 연습으로 저는 은행 계좌라는 클래스를 만들고 DisplayBalance(), Withdrawals() 및 Transaction() 메소드를 구현하려고했습니다.PHP 클래스 및 메소드 초급

대부분은 작동하며 계좌에서 '돈'을 더하거나 뺍니다.하지만 균형을 제거하기 위해 초기 잔액을 초과하여 돈을 인출 할 때도하고 싶습니다. 메시지를 보내고 예를 들어 '더 많은 돈'을 넣으십시오.

현재 오류 메시지가 나타나지만 잔액도 표시됩니다. 누군가가 올바른 방향으로 나를 가리킬 수 조용히 좌절 나는 수업과 방법으로 내 경험을 즐기기 시작했다!

내 코드 :

<?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(); 

?> 
+3

, 당신은 당신이 얻을 출력을 제공 할 수 바랍니다 시도 할 수 있습니까? 그리고 원하는 출력? –

+1

메서드 안에 아무 것도 울려서는 안됩니다. 오히려 문자열 대신 문자열을 반환하게하십시오. 코드를 쉽게 유지 관리 할 수 ​​있습니다. –

+0

아마도 if (($ this-> balance) <0)'는'if (($ this-> balance) <= 0)'이어야합니다. – MeNa

답변

2

먼저 (12)을 철회하고있어,이 일이 무엇 :

if (($this->balance)<$amount){ 
    echo 'Not Enough Founds: '.'</br>'; 

을 그리고 그것 뿐이다, 더 빼기는 실행되지 않습니다. $에 인수 - 그냥 오류에 공감 한 및 $ this-> 균형을하지 않은 이전의 기능과 균형이 여전히 10.5>

public function DisplayBalance(){ 
    if(($this->balance)<0){ 
     return false; 
    }else{ 
     return 'Balance: '.$this->balance.'</br>'; 
    } 
} 

음, $ 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; 
    } 
} 
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();