【问题标题】:Break method chaining in php打破php中的方法链接
【发布时间】:2010-02-08 05:14:05
【问题描述】:

我正在为我的类结构使用方法链。

所以我的问题是,当某些功能发生错误时,我怎么能打破我的链条。

下面是我的代码:

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

?>

编辑:

$demoClass = new demo();

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

谢谢

阿维纳什

【问题讨论】:

    标签: php oop class methods method-chaining


    【解决方案1】:

    我认为你需要在那里抛出用户异常

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

    【讨论】:

    • 那么我应该在哪里处理这个异常呢?
    • @Avinash:在这里您只需抛出异常即可跳过。有关更多信息,请参阅此内容:php.net/manual/en/language.exceptions.php
    • 所以我的类函数调用应该和我编辑我的问题一样?请确认....
    • @Avinash:是的,你可以试试看。
    • @Avinash:那真是个好消息 :)
    猜你喜欢
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2014-12-29
    • 2011-06-13
    • 2012-11-20
    • 1970-01-01
    相关资源
    最近更新 更多