2012-03-10 162 views
1

我不斷收到這個錯誤對於錯誤的陣列,我的方法中的foreach()錯誤警告:()提供的foreach無效參數

這裏有設置是代碼

public function showerrors() { 
     echo "<h3> ERRORS!!</h3>"; 
     foreach ($this->errors as $key => $value) 
     { 
      echo $value; 
     } 
    } 

我保持得到這個「警告:提供的foreach()無效參數」當我運行程序 我設置了錯誤陣列在構造這樣

$this->errors = array(); 

所以我不會完全知道爲什麼它不會打印錯誤!

public function validdata() { 
     if (!isset($this->email)) { 
      $this->errors[] = "email address is empty and is a required field"; 
     } 

     if ($this->password1 !== $this->password2) { 
      $this->errors[] = "passwords are not equal "; 
     } 
     if (!isset($this->password1) || !isset($this->password2)) { 
      $this->errors[] = "password fields cannot be empty "; 
     } 
     if (!isset($this->firstname)) { 
      $this->errors[] = "firstname field is empty and is a required field"; 
     } 
     if (!isset($this->secondname)) { 
      $this->errors[] = "second name field is empty and is a required field"; 
     } 

     if (!isset($this->city)) { 
      $this->errors[] = "city field is empty and is a required field"; 
     } 


     return count($this->errors) ? 0 : 1; 
    } 

這裏是我如何添加數據到數組本身!感謝您的幫助!

好吧,我加入這

public function showerrors() { 
     echo "<h3> ERRORS!!</h3>"; 
     echo "<p>" . var_dump($this->errors) . "</p>"; 
     foreach ($this->errors as $key => $value) 
     { 
      echo $value; 
     } 

然後將其輸出我的網頁上這

錯誤的方法! 字符串(20)「無效提交!!」如果我沒有輸入任何東西到我的文本框,所以它說一個字符串?

這裏是我的構造函數也soory關於這個即時通訊新的PHP!

public function __construct() { 

     $this->submit = isset($_GET['submit'])? 1 : 0; 
     $this->errors = array(); 
     $this->firstname = $this->filter($_GET['firstname']); 
     $this->secondname = $this->filter($_GET['surname']); 
     $this->email = $this->filter($_GET['email']); 
     $this->password1 = $this->filter($_GET['password']); 
     $this->password2 = $this->filter($_GET['renter']); 
     $this->address1 = $this->filter($_GET['address1']); 
     $this->address2 = $this->filter($_GET['address2']); 

     $this->city = $this->filter($_GET['city']); 
     $this->country = $this->filter($_GET['country']); 
     $this->postcode = $this->filter($_GET['postcode']); 


     $this->token = $_GET['token']; 
    } 
+0

發佈更多代碼。我敢打賭,你試圖添加到'$ this-> errors'的某個地方,卻意外地使用了'='而不是'[] =',並最終用一個標量覆蓋它... – 2012-03-10 14:32:39

+0

我有時會遇到一個常見的錯誤當我輸入的速度太快的時候做自己是'$ this-> errors ='foo';'而不是'$ this-> errors [] ='foo';'。就這個代碼而言,這不是問題。 – netcoder 2012-03-10 14:32:54

+3

使用var_dump檢查foreach之前發生的事情。 – 2012-03-10 14:35:34

回答

1

上的默認(沒有填寫)驗證,以您的形式,其中消息"invalid submission"設置,你離開了括號[],造成$this->errors與普通字符串,而不是追加到數組被覆蓋。

// Change 
$this->errors = "invalid submission"; 

//...to... 
$this->errors[] = "invalid submission"; 
+0

謝謝Michael!是的,這確實是問題! – eoin 2012-03-10 16:36:27

相關問題