【发布时间】:2013-01-13 17:39:25
【问题描述】:
假设有一个对象类,让我们以 User 为例。 User 类包含它自己的规则,用于在提交之前验证它的数据。在保存到数据库之前,将检查规则并返回任何错误。否则更新将运行。
class User extends DBTable // contains $Rules, $Data, $Updates, and other stuff
{
public __construct($ID)
{
parent::__construct($ID);
// I'll only list a couple rules here...
$this->Rules['Email'] = array(
'Empty' => 'ValidateEmpty', // pre-written functions, somewhere else
'Invalid' => 'ValidateBadEmail', // they return TRUE on error
'Duplicate' => function($val) { return existInDatabase('user_table', 'ID_USER', '`Email`="'. $val .'" AND `ID_USER`!='. $this->ID);}
);
$this->Rules['Password'] = array(
'Empty' => 'ValidateEmpty',
'Short' => function($val) { return strlen($val) < 8; }
);
this->Rules['PasswordConfirm'] = array(
'Empty' => 'ValidateEmpty',
'Wrong' => function($val) { return $val != $this->Updates['Password']; }
);
}
public function Save(&$Errors = NULL)
{
$Data = array_merge($this->Data, $this->Updates);
foreach($this->Rules as $Fields => $Checks)
{
foreach($Checks as $Error => $Check)
{
if($Check($Data[$Field])) // TRUE means the data was bad
{
$Errors[$Field] = $Error; // Say what error it was for this field
break; // don't check any others
}
}
}
if(!empty($Errors))
return FALSE;
/* Run the save... */
return TRUE; // the save was successful
}
}
希望我在这里发布的足够多。因此,您会注意到,在电子邮件的 Duplicate 错误中,我想检查他们的新电子邮件是否不存在于除他们自己之外的任何其他用户。 PasswordConfirm 还尝试使用 $this->Updates['Password'] 来确保他们两次输入相同的内容。
当 Save 运行时,它会遍历规则并设置所有存在的错误。
这是我的问题:
Fatal error: Using $this when not in object context in /home/run/its/ze/germans/Class.User.php on line 19
我想使用 $this 的所有闭包都会出现此错误。
似乎数组中的闭包和类中的数组的组合导致了问题。这个规则数组的东西在类之外工作正常(通常涉及“使用”),AFAIK 闭包应该能够在类中使用 $this。
那么,解决方案?解决方法?
谢谢。
【问题讨论】:
-
如果你有 PHP 5.4,你必须使用
use ($this)作为闭包的一部分。如果你有 PHP 5.3,我认为你必须复制$this -
哪个 PHP 版本?在 5.4 之前无法将闭包绑定到
$this -
谢谢大家。你是对的,我只是为错误的 PHP 版本编程。更新 PHP 解决了。