链接方法时如何返回false [英] How to return false when chaining methods

查看:72
本文介绍了链接方法时如何返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用方法链的验证类.我希望能够像这样使用 TRUE/FALSE 进行单一检查:

I have a validation class which uses method chaining. I would like to be able to do single checks with TRUE/FALSE like this:

if ($obj->checkSomething()) {}

还有像这样的链式方法:

But also chain methods like this:

if ($obj->checkSomething()->checkSomethingElse()) {}

然而,问题是如果一个方法返回FALSE,它不会发回一个对象,从而破坏以这个错误结束的方法链:

The problem however is that if one method returns FALSE, it will not send back an object and thus breaks the method chaining which ends with this error:

Fatal error: Call to a member function checkSomething() on a non-object in ...

我是否必须选择单个方法返回调用或方法链,或者是否有解决方法?

Do I have to pick either single method return calls or method chaining or is there a workaround?

推荐答案

一个想法是设置一个内部标志来指示成功或失败,并通过另一种方法访问它,同时在每个方法中检查该标志而不做任何事情如果设置了.例如:

One idea would be to set an internal flag to indicate success or failure, and access it via another method, while checking that flag in each method and not doing anything if it's set. E.g.:

class A {
    private $valid = true;

    public function check1() {
        if (!$this->valid) {
            return $this;
        }
        if (!/* do actual checking here */) {
            $this->valid = false;
        }
        return $this;
    }
    public function check2() {
        if (!$this->valid) {
            return $this;
        }
        if (!/* do actual checking here */) {
            $this->valid = false;
        }
        return $this;
    }
    public function isValid() {
        return $this->valid;
    }
}

// usage:

$a = new A();

if (!$a->check1()->check2()->isValid()) {
    echo "error";
}

为了尽量减少每个函数中的样板检查,您还可以使用魔术方法 __call().例如:

To minimize the boilerplate checking in each function, you could also use the magic method __call(). E.g.:

class A {
    private $valid;
    public function __call($name, $args) {
        if ($this->valid) {
            $this->valid = call_user_func_array("do" . $name, $args);
        }
        return $this;
    }
    private function docheck1() {
        return /* do actual checking here, return true or false */;
    }
    private function docheck2() {
        return /* do actual checking here, return true or false */;
    }
    public isValid() {
        return $this->valid;
    }    
}

用法和上面一样:

$a = new A();

if (!$a->check1()->check2()->isValid()) {
    echo "error";
}

这篇关于链接方法时如何返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆