我正在寻找类似break
for循环的东西.
这里是一些示例代码(使用Symfony的石灰),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();
从内部打电话stop()
似乎没有办法.是否有一个我可以调用的函数可以stop()
实现这一点?
您可以使用PHP异常:
// 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();
只需返回另一个类,它将为每个调用的方法返回$ 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