2010-02-08 2 views
1

Я использую метод chaining для моей структуры класса.Метод разрыва метода в php

Так что моя проблема в том, что, как я могу сломать свою цепочку, когда в какой-то функции возникла ошибка.

Ниже мой код:

<?php 
    class demo 
    { 
     public __construct() 
     { 
      $this->a='a'; 
      $this->b='b'; 
      $this->error = false; 
     } 

     public function demo1() 
     { 
      // Some operation here 
      // Now based on that operation 

      if(Operation success) 
      { 
       return $this; 
      } 
      else 
      { 
       // What should i write here which break the chain of methods. 
       // It will not execute the second function demo2 
      } 
     } 

     public function demo2() 
     { 
      // Some operation here 
      // After function Demo1 
     } 

    } 

    $demoClass = new demo(); 

    $demoClass->demo1()->demo2(); 

?> 

EDIT:

$demoClass = new demo(); 

    try 
    { 
     $demoClass->demo1()->demo2(); 
    } 
    catch(Exception $e) 
    { 
     echo "Caught Exception:->".$e->getMessage(); 
    } 

Благодаря

Авинаш

ответ

3

Я думаю, что нужно бросить исключение пользователя там.

 if(Operation success) 
     { 
      return $this; 
     } 
     else 
     { 
      // What should i write here which break the chain of methods. 
      // It will not execute the second function demo2 

      throw new Exception('error'); 
     } 
+0

Так где же я должен справиться с этим исключением? – Avinash

+0

@Avinash: здесь вы просто бросаете исключение, чтобы пропустить. см. это для получения дополнительной информации, поскольку есть еще что-то: http://php.net/manual/en/language.exceptions.php – Sarfraz

+0

Итак, мой вызов функции класса должен быть таким, как я отредактировал свой вопрос? Пожалуйста, подтвердите .... – Avinash

Смежные вопросы