【问题标题】:PHP Fatal error: Call to protected method FormValidator::setError() from context ''PHP 致命错误:从上下文“”调用受保护的方法 FormValidator::setError()
【发布时间】:2011-01-25 21:46:45
【问题描述】:

想想我可怜的班级:

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 '' ...

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

【问题讨论】:

    标签: php class closures currying


    【解决方案1】:

    显然不是原生的。 This manual note 提出了一种相当麻烦的方法,即使用反射和包装类来为闭包提供私有/受保护的访问功能。

    【讨论】:

    • 我检查了它,它似乎可以工作,但没有人会使用它,因为显然它在性能方面的成本太高了。无论如何,谢谢你,这是一本非常有教育意义的读物。
    • @fabio:是的,我猜我的意思是你不能轻易做到这一点。不幸的是,真的。
    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 2010-11-02
    • 2016-02-19
    • 2015-12-08
    • 2015-05-13
    • 2020-08-02
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多