search

Home  >  Q&A  >  body text

How to return information in the middle of PHP chain calls

How to get error information when there is an error in PHP chain call

The error message here is not a simple string. For example, during the chain call process, a certain function may need to return an array when it does not meet a certain condition, and directly report an error, saying that the array cannot call the next function, but how? Is it possible to stop calling further when a certain function in the middle returns?

学习ing学习ing2705 days ago1063

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你2017-07-05 10:48:11

    try catch

    reply
    0
  • 習慣沉默

    習慣沉默2017-07-05 10:48:11

    Is it like this below?

    <?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: It feels like writing golang

    Play online https://glot.io/snippets/ereygerdv3

    reply
    0
  • 高洛峰

    高洛峰2017-07-05 10:48:11

    throw new \Exception('error');

    reply
    0
  • Cancelreply