views:

191

answers:

1

Hi

I am using method chaining for my class structure.

So my problem is that , how could i break my chain when error occurred in some function.

Below is my code:

 <?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();
    }   

Thanks

Avinash

+3  A: 

I think you need to throw user exception there.

        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');
        }
Sarfraz
So where should i handle this exception?
Avinash
@Avinash: here you just throw the exception to skip out. see this for more info as there is more to it: http://php.net/manual/en/language.exceptions.php
Sarfraz
So my class function call should be as i have edited my Question? Please confirm....
Avinash
@Avinash: yes you may try it out.
Sarfraz
Thanks a lot it works.... :-)
Avinash
@Avinash: It is great news then :)
Sarfraz