Avinash
Avinash

Reputation: 6174

Break method chaining in php

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

Upvotes: 1

Views: 2035

Answers (1)

Sarfraz
Sarfraz

Reputation: 382909

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');
        }

Upvotes: 3

Related Questions