2012-06-02 137 views
0

我試圖在窗體上顯示錯誤消息,但只顯示一個(最後一個總是)。我嘗試使用foreach循環,但我不斷收到無效的參數錯誤。以下顯示錯誤一個接一個。代碼是一個類的內部...PHP foreach提供的參數無效

public $errorContainer = ''; 

// ------------------------------------------------------------ 
// ERROR MESSAGE PROCESSING 
// ------------------------------------------------------------ 
private function responseMessage($respBool, $respMessage) { 
    $return['error'] = $respBool; 
    $return['msg'] = $respMessage; 
    if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) { 
     echo json_encode($return); 
    } else { 
     $this->errorContainer = $respMessage; 
    } 
} 

下總是讓我對每一個參數錯誤的無效。

private function responseMessage($respBool, $respMessage) { 
    $return['error'] = $respBool; 
    $return['msg'] = $respMessage; 
    if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) { 
     echo json_encode($return); 
    } else { 
     foreach ($respMessage as $value) { 
      $this->errorContainer = $value; 
     } 
    } 
} 

謝謝!

+1

'$ respMessage'是一個數組嗎? – nickb

+0

這個函數是如何調用的? –

+0

此函數未被調用 - $ errorContainer爲。對不起,它應該顯示爲私人而不是公開。我的意思是隻在班級內部呼叫的功能。 $ this-> responseMessage(true,$ msg); – user1002039

回答

1

取代你foreach()本:

private function responseMessage($respBool, $respMessage) { 
    // ...code... 
    foreach ((array) $respMessage as $value) { 
    $this->errorContainer .= $value; 
    } 
    // ...code--- 
} 

使用上述類型的鑄造(array)將使它同時適用於數組和字符串類型。

編輯:

使用此解決方案(壓鑄類)僅在最後的努力。但是你真正的問題是你沒有將數組傳遞給函數。看到這個代碼:如果你正確地傳遞參數類似上面

// incorrect 
$msg = 'This is a message'; 
$this->responseMessage($some_bool, $msg); 

// correct 
$msg = array('This is a message'); 
$this->responseMessage($some_bool, $msg); 

// correct 
$msg = array('This is a message', 'And another message'); 
$this->responseMessage($some_bool, $msg); 

,你不需要投$respMessage數組。

+0

但我仍然收到爲foreach()錯誤提供的無效參數。 – user1002039

+0

它看起來像傳遞給函數的'$ respMessage'不是一個數組。你可以像編輯的代碼一樣將'$ respMessage'強制轉換爲數組。 – flowfree

+1

我同意concat,但這個演員並不是真正的解決方案。問題在於。 – zessx