How to return information in the middle of PHP chain calls
学习ing
学习ing 2017-07-05 10:46:11
0
3
1059

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
学习ing

reply all(3)
世界只因有你

try catch

習慣沉默

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

小葫芦

throw new \Exception('error');

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template