我有一个使用方法链的验证类。我希望能够进行单次检查TRUE/FALSE
像这样:
if ($obj->checkSomething()) {}
但也有像这样的链方法:
if ($obj->checkSomething()->checkSomethingElse()) {}
然而问题是,如果一种方法返回FALSE
,它不会发回对象,从而破坏方法链,并以此错误结束:
Fatal error: Call to a member function checkSomething() on a non-object in ...
我是否必须选择单一方法返回调用或方法链接,或者是否有解决方法?
一种想法是设置一个内部标志来指示成功或失败,并通过另一种方法访问它,同时检查每个方法中的该标志,如果设置了该标志,则不执行任何操作。例如。:
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()
. 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";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)