1

考虑我的可怜的班级:

abstract class FormValidator
{
    private $error_objects = array();

    protected function setError($entry_name,$err_msg)
    {
        $this->error_objects[] = 
            new FormValidatorErrorObject($entry_name,$err_msg);
    }

    protected function setErrorCurry($entry_name)
    {
        $_this = $this;
        return function($err_msg) use($entry_name,$_this)
        {
            return $_this->setError($entry_name,$err_msg);
        };
    }

    public function countErrors()
    {
        return count($this->error_objects);
    }

    public function getError($index)
    {
        return $this->error_objects[$index];
    }

    public function getAllErrors()
    {
        return $this->error_objects;
    }

    abstract function validate();
}

我在这样的实现类中使用它:

$setError = $this->setErrorCurry('u_email');
    if(empty($uemail))
    {
        $setError(uregform_errmsg_email_null);
    }

    if(!filter_var($uemail,FILTER_VALIDATE_EMAIL))
    {
        $setError(uregform_errmsg_email_invalid);
    }

这会导致以下错误:

Fatal error: Call to protected method FormValidator::setError() from context '' ...

问题:有没有办法让闭包“继承”类上下文?

4

1 回答 1

1

显然不是原生的。本手册说明了一种相当麻烦的方式,即使用反射和包装类来为闭包提供私有/受保护的访问功能。

于 2011-01-25T21:52:55.623 回答