PHP链式调用如何在中间返回信息

PHP链式调用如何在中间错误的时候拿到错误信息

这里的错误信息不是简单的字符串,比如链式调用过程中可能某一个函数在不满足某个条件的时候,需要返回一个数组,直接报错,说数组无法调用下一个函数,但是如何能做到在中间某个函数返回的条件下不再往后继续调用呢?

阅读 4.1k
3 个回答

是不是下面的这个样子呢?

<?php

class Demo
{
    protected $result;
    protected $error = false;
    
    function funcA() 
    {
        if (! $this->error) {
            //do xxx
        }
        
        return $this;
    }
    
    function funcB() 
    {
        if (! $this->error) {
            //do xxx
            //模拟发生错误
            $this->error = true;
            $this->result = ['Ops!', 'Something bad Happened!'];
        }
        
        return $this;
    }
    
    function funcC() 
    {
        if (! $this->error) {
            //do xxx
        }
        
        return $this;
    }
    
    function GetResult() {
        return [$this->result, $this->error];
    }
}

$demo = new Demo();

list($result, $hasError) = $demo->funcA()->funcB()->funcC()->GetResult();

var_dump($result, $hasError);

PS: 感觉写出了 golang 的感觉

在线把玩 https://glot.io/snippets/ereygerdv3

throw new \Exception('error');

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题