代码之家  ›  专栏  ›  技术社区  ›  thrashr888

如何阻止PHP类执行?

  •  5
  • thrashr888  · 技术社区  · 17 年前

    我在找像这样的东西 break

    stop() 不会让课程继续和 I_DONT_WANT_THIS_TO_RUN() 不会被处决。

    $browser->isStatusCode(200)
      ->isRequestParameter('module', 'home')
      ->isRequestParameter('action', 'index')
      ->click('Register')
      ->stop()
      ->I_DONT_WANT_THIS_TO_RUN();
    $browser->thenThisRunsOkay();
    

    $this->__deconstruct(); 停止() 停止() 那会实现吗?

    3 回复  |  直到 17 年前
        1
  •  10
  •   Paige Ruten    17 年前

    你可以用 PHP exceptions :

    // This function would of course be declared in the class
    function stop() {
        throw new Exception('Stopped.');
    }
    
    try {
        $browser->isStatusCode(200)
          ->isRequestParameter('module', 'home')
          ->isRequestParameter('action', 'index')
          ->click('Register')
          ->stop()
          ->I_DONT_WANT_THIS_TO_RUN();
    } catch (Exception $e) {
        // when stop() throws the exception, control will go on from here.
    }
    
    $browser->thenThisRunsOkay();
    
        2
  •  6
  •   OIS    17 年前

    只需返回另一个类,该类将为每个调用的方法返回$this。

    例子:

    class NoMethods {
        public function __call($name, $args)
        {
            echo __METHOD__ . " called $name with " . count($args) . " arguments.\n";
            return $this;
        }
    }
    
    class Browser {
        public function runThis()
        {
            echo __METHOD__ . "\n";
            return $this;
        }
    
        public function stop()
        {
            echo __METHOD__ . "\n";
            return new NoMethods();
        }
    
        public function dontRunThis()
        {
            echo __METHOD__ . "\n";
            return $this;
        }
    }
    
    $browser = new Browser();
    echo "with stop\n";
    $browser->runThis()->stop()->dontRunThis()->dunno('hey');
    echo "without stop\n";
    $browser->runThis()->dontRunThis();
    echo "the end\n";
    

    将导致:

    with stop
    Browser::runThis
    Browser::stop
    NoMethods::__call called dontRunThis with 0 arguments.
    NoMethods::__call called dunno with 1 arguments.
    without stop
    Browser::runThis
    Browser::dontRunThis
    the end
    
        3
  •  1
  •   nickf    17 年前

    OIS的答案非常好,尽管我可以看出,如果对象突然变为其他对象,它可能会变得混乱。也就是说,您希望在链的末尾,您将以相同的对象结束。为了避免这个问题,我添加了一个私有变量来告诉类是否实际执行任何操作。如果类已停止,则每个类都将返回 $this 马上。这为您提供了能够重新启动执行的额外好处。

    class MyClass {
        private $halt;
    
        function __call($func, $args) {
            if ($this->halt) {
                return $this;
            } else {
                return $this->$func($args);
            }
        }
    
        private function isRequestParameter() {
            // ...
        }
        public function stop() {
            $this->halt = true;
        }
        public function start() {
            $this->halt = false;
        }
    }
    

    可以将其放入父类中,这样就不必重复此代码。

    推荐文章