2015-09-18 203 views
0

所以我希望做一個函數來顯示的,而不是說echo "error message"的錯誤,我想是這樣$this->errorDisplay('error message');錯誤處理PHP函數

我現在有這一點,但它不是做的工作。

function errorDisplay($msg) { 
    $this->errors[] = $msg; 

    foreach($this->errors as $error) { 
    echo $error; 
    } 

} 

public function checkFields($username,$password) { 
    if(!empty($username) && !empty($password)) { 
     //proceed to validation 
    } else { 
     $this->errorDisplay('All fields are required.'); 
    } 
} 
+3

你的函數一次做兩件事:收集消息,並輸出先前收集的消息。如果這是你真正想做的事情,請將它分開。 – mario

+0

你想要發生什麼? –

+0

如果你只是想顯示一個錯誤,你爲什麼要把所有的錯誤放在一個數組中? – Barmar

回答

1

,而不是試圖在一個方法做的一切,分裂過程成2.一種方法增加了消息的數組,另一個顯示所有以前保存起來的消息。

Class xxx 
{ 

    public $errors = array(); 

    public function addError($msg) { 
     $this->errors[] = $msg; 
    } 

    public function showErrors() { 
     foreach($this->errors as $error) { 
      echo $error; 
     } 
    } 

    public function initErrors() { 
     $this->errors = array(); 
    } 

    public function checkFields($username,$password) { 

     $this->initErrors(); 

     if(empty($username) ) { 
      $this-addError('Username missing'); 
     } 
     if (empty($password)) { 
      $this-addError('Password missing'); 
     } 

     if (count($this->errors) > 0) { 
      $this->showErrors(); 
     } 
    } 
} //end class