【问题标题】:$this in Array of Closures in Class$this 在类中的闭包数组中
【发布时间】: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 解决了。

标签: php class closures


【解决方案1】:

问题出在Wrong 验证器上。从这里调用验证方法:

if($Check($Data[$Field])) // TRUE means the data was bad

此调用不是在对象上下文中进行的(lambda 不是类方法)。因此,lambda 主体内的$this 会导致错误,因为它仅在对象上下文中存在。

对于 PHP >= 5.4.0,您可以通过捕获$this 来解决问题:

function($val) { return $val != $this->Updates['Password']; }

在这种情况下,您将能够访问Updates,无论其可见性如何。

对于 PHP >= 5.3.0,您需要复制对象引用并捕获它:

$self = $this;
function($val) use($self) { return $val != $self->Updates['Password']; }

但是,在这种情况下,您将只能访问 Updates,如果它是 public

【讨论】:

  • 谢谢。在如何使用 $this 的所有这些修改中一定错过了它。我更新了我的 PHP 版本来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 2012-04-08
  • 2018-02-19
相关资源
最近更新 更多