How to catch the error at the moment when the condition is false and the function does not return the object? I guess that it is necessary to use exceptions, but I never used them, I will be grateful for an example.

class hub{ public function r($condition,$message){ if ($condition){ echo $message; return $this; }else{ return 0; } } } $o=new hub(); $o->r(true,'continue ')->r(true,'continue')->r(true,'continue')->r(false,'stop')->r(true,'continue'); 

    2 answers 2

    You can certainly do this:

     try{ if ($condition){ echo $message; return $this; } else{ throw new Exception('Error'); } } 

    And then catch the catch exception. But I do not understand the sacred meaning of this operation. For me, it's better to do something like this:

     if($condition && !$this->errorFlag){ //... } else{ $this->errorFlag = true; } return $this; 

    This construction is debugged in exactly the same way - via echo or internal call counter.

    • Well, in fact, I just need to break the chain and continue the program execution. UPD Well, although yes you can, and so and so you are right. - culebre

    Maybe using exceptions:

     class hub{ public function r($condition,$message){ if ($condition){ echo $message; }else{ throw new Exception( '$condition is false, with $message="' . $message . '"' ); } return $this; } } 

    Respectively:

     $o=new hub(); try { $o->r(true,'continue') ->r(true,'continue') ->r(true,'continue') ->r(false,'stop') ->r(true,'continue'); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } 

    Accordingly, you can make your own class of exceptions and describe in detail the reason for what happened.