I was wondering if PHP has a function that allows me to end a process before it reaches the "?>" tag, example:
<?php
echo 'first';
endphptag();
echo 'second';
?>
third
<?php
echo 'fourth';
?>
Then the output should be:
first
third
fourth
I know that some people consider this as something useless, but I want to do it for a validation script on an iframe instead of use the die
or exit
function because it kills the whole script, I just want to end a part of it.
Normally I use if - else
instead, but I want to avoid them because the processes are large and I want something more readable, by the way I use if - die
in my ajax scripts and I want to use something like this in my iframes too, Thank's!
Well, I just wanted to know if PHP already had a proper function for it (it seems not), so I think I will just leave it with if - elses, because is not really worth to use more process for make it "more readable" (ex: try - catches uses too much resources, I'm not going to go-tos neither). My doubt was only for that, I will only use this procesdure in my ajax files using the die function (I don't know if it is recommended, but I think there's no problem because PHP should have it for some reason)
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.
The exit() method is only used to exit the process. The die() function is used to print the message. The exit() method exits the script or it may be used to print alternate messages.
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.
You can't break if statements, only loops like for or while. If this if is in a function, use 'return'.
Exceptions is what you are looking for:
try {
// code
} catch (Exception $e) {
// handling
}
You put your code inside the try block and you end it throwing an exception with throw new Exception();
, and it exits only the rest of the code inside the try block.
Your code would then be:
<?php
try {
echo 'first';
throw new Exception();
echo 'second';
} catch (Exception $e) {}
?>
third
<?php
echo 'fourth';
?>
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