当前位置:  开发笔记 > 编程语言 > 正文

你如何阻止PHP类执行?

如何解决《你如何阻止PHP类执行?》经验,为你挑选了2个好方法。

我正在寻找类似breakfor循环的东西.

这里是一些示例代码(使用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()实现这一点?



1> Jeremy Ruten..:

您可以使用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();



2> OIS..:

只需返回另一个类,它将为每个调用的方法返回$ 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

推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有