gpt4 book ai didi

php - 链接方法时如何返回 false

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:38 25 4
gpt4 key购买 nike

我有一个使用方法链的验证类。我希望能够像这样使用 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()。例如:

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";
}

关于php - 链接方法时如何返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com