7

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

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

 common_code();
 exit();

3 Answers 3

26

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 https://www.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');
?>
Sign up to request clarification or add additional context in comments.

Comments

8

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

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.