的foreach()错误警告:()提供的foreach无效参数
问题描述:
我不断收到这个错误对于错误的阵列,我的方法中的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'];
}
答
上的默认(没有填写)验证,以您的形式,其中消息"invalid submission"
设置,你离开了括号[]
,造成$this->errors
与普通字符串,而不是追加到数组被覆盖。
// Change
$this->errors = "invalid submission";
//...to...
$this->errors[] = "invalid submission";
+0
谢谢Michael!是的,这确实是问题! – eoin 2012-03-10 16:36:27
发布更多代码。我敢打赌,你试图添加到'$ this-> errors'的某个地方,却意外地使用了'='而不是'[] =',并最终用一个标量覆盖它... – 2012-03-10 14:32:39
我有时会遇到一个常见的错误当我输入的速度太快的时候做自己是'$ this-> errors ='foo';'而不是'$ this-> errors [] ='foo';'。就这个代码而言,这不是问题。 – netcoder 2012-03-10 14:32:54
使用var_dump检查foreach之前发生的事情。 – 2012-03-10 14:35:34