views:

236

answers:

3

How can something like the following be done in a PHP script?

 code{
      $result1 = task1() or break;
      $result2 = task2() or break;
 }

 common_code();
 exit();
+4  A: 

if you use OOP then you could put the code you want to execute on exit into the destructor of your class.

class example{
   function __destruct(){
      echo "Exiting";
   }
}
Mikey
+13  A: 

From the PHP help doco you can specify a function that is called after exit() but before the script ends.

Feel free to check the doco for more info http://us3.php.net/manual/en/function.register-shutdown-function.php

<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
Jai
+3  A: 

Your example is probably too simplistic, as it can easily be re-written as follows:

if($result1 = task1()) {
    $result2 = task2();
}

common_code();
exit;

Perhaps you are trying to build flow-control like this:

do {
    $result1 = task1() or break;
    $result2 = task2() or break;
    $result3 = task3() or break;
    $result4 = task4() or break;
    // etc
} while(false);
common_code();
exit;

You can also use a switch():

switch(false) {
case $result1 = task1(): break;
case $result2 = task2(): break;
case $result3 = task3(): break;
case $result4 = task4(): break;
}

common_code();
exit;

Or in PHP 5.3 you can use goto:

if(!$result1 = task1()) goto common;
if(!$result2 = task2()) goto common;
if(!$result3 = task3()) goto common;
if(!$result4 = task4()) goto common;

common:
echo "common code\n";
exit;
too much php