How can something like the following be done in a PHP script?
code{
$result1 = task1() or break;
$result2 = task2() or break;
}
common_code();
exit();
The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.
Or I need to write die() or exit() before the end of php script? No. When the script reaches the end, it will exit anyway. It is only useful if someone may be interested in the return code of your script, like when you use it in a shell environment.
The return keyword ends a function and, optionally, uses the result of an expression as the return value of the function. If return is used outside of a function, it stops PHP code in the file from running.
Definition and Usage. The die() function is an alias of the exit() function.
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');
?>
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";
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With