How do you stop executing a PHP class?

I am looking for something like break for loops.

Here's some sample code (using Symfony lime) where stop() will not allow the class to continue, and I_DONT_WANT_THIS_TO_RUN() will not be executed.

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

Call $this->__deconstruct(); from inside stop() doesn't seem to do this trick. Is there a function that I can call inside stop() , what could happen?

+4
source share
3 answers

Just return another class that will return $ this for each method called.

Example:

 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"; 

will result in:

 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 
+6
source

You can use 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(); 
+10
source

The OIS answer is really good, although I could see that there might be confusion if the object suddenly changes to something else. That is, you expect that at the end of your chain you will get the same object. To avoid this problem, I would add a private variable to tell the class whether to really do anything. If the class was stopped, each class immediately returns $this . This gives you the added benefit of restarting execution.

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

This can be placed in the parent class, so you do not need to duplicate this code.

+1
source

All Articles