开发者

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:-&开发者_如何学运维gt;".$e->getMessage();
    }   

Thanks

Avinash


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜