2012-06-02 132 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