php 链接返回,php – 链接方法时如何返回false

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

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值