This question already has answers here:
Why is the semicolon optional in the last statement in php?
(3 answers)
Closed 6 years ago.
Today I have a little weird question.
Should I end my PHP script with exit or exit; and which is correct?.
Without ;
and
With ;
Thanks.
exit, exit;, exit(), and exit(); are exactly the same, but the fact is that you should not end your script with an exit() call, it's just bad practice (but it works).
EDIT
Clarifying why i said it's "bad practice", it's not about the functionality of "exit" itself, it's OK to halt the script execution if something bad happens, but the concept of "something bad" is really wide. In general, even if some unwanted condition occurs, the normal execution flow should reach to the end of the file. Just consider this example:
...some init stuff...
if (!user_is_authenticated) {
...print some nasty message...
exit();
}
...continue with normal stuff...
A better approach would be:
...some init stuff...
if (user_is_authenticated) {
...continue with normal stuff...
}
else {
...print some nasty message...
}
What's the difference? The difference is that in the second version you don't need to use exit(), which means if one day you need to do something after BOTH the "normal" and "unwanted" execution flows you can just add it at the end of the file.
It's more or less the same argument about why you should NOT use "return" in function bodies except at the end of the function..
It is allways a good practise to use semicolon
<?php
//exit program normally
exit;
exit();
exit(0);
//exit with an error code
exit(1);
exit(0376); //octal
?>
Like Johnny said, all those four forms of 'exit' statement work. Both exit and exit() work if there is no statements followed by any of these two language constructs. It doesn't work if there is any other PHP statements followed by these two constructs and semicolon's purpose is to end the statement to proceed to the next statement, therefore you need to use exit; or exit(); to avoid syntax error and also, in this case, without using semicolon is considered to be a bad practice in the coding conventions.
Related
This question already has answers here:
Why would one omit the close tag?
(14 answers)
Closed 6 years ago.
Should I close PHP tags after die or exit functions or it is not necessary?
You'd still need to make sure your PHP is syntactically valid, even if the script might exit mid-point somewhere.
e.g. this will not work:
<?php
if (true) {
die();
}
<html>
would not valid, because the PHP parser will barf on <html> - you're still in PHP mode, and <html> is not valid PHP code.
The script execution would never reach the tag, so theoretically it shouldn't matter that you don't have ?>, but the parser doesn't check if something is logically reachable, it just checks the raw syntax.
According to the docs, only omit the closing tag if it's at the end of the file:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
-- http://php.net/manual/en/language.basic-syntax.phptags.php
This applies to exit and die calls as well. They would run through the same parser as the rest of your php code.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I am having a problem with putting partial bits of PHP code into an include file. Essentially, the situation is like in the following example:
<?php
$x=1;
if ($x==1) { echo 'test'; }
?>
This yields test.
I now replace this with
<?php
$x=1;
if ($x==1) { include('test_incl.php') ;
?>
with test_incl.php
<?php echo 'test'; } ?>
As the include file just adds the code back on that was taken out in the original code, I would expect it to work as well, but instead I am getting "Parse error: syntax error, unexpected end of file".
Any clues what is going on here?
A further explanation:
I need to put a conditional around a block of code in one language version of our shopping cart but not others. So my idea was to include the PHP files where the opening and closing part of the conditionals should be, which would keep the core code for all versions identical, with only the includes differing (this how the language specific features are dealt with anyway for this shopping cart).
From what I have read, the PHP engine parses the includes in the flow of the code, so I don't understand why I get the end of file error (which suggests that the include has actually not been parsed yet when the end of the parent code is reached.
Also, I have used this kind of method successfully before with Javascript/HTML includes.
You can't include opening and closing tags of the if statement like that in separate files, so when your main file gets to the end of the file the if statement is still open, hence the unexpected eof.
To fix this you need to move the closing brace of the if statement back into the original file. Your files should look like this:
<?php
$x=1;
if ($x==1) { include('test_incl.php'); }
?>
and test_incl.php:
<?php echo 'test'; ?>
Try this:
<?php
$x=1;
if ($x==1) {
include('test_incl.php');
}
?>
and
<?php echo 'test';?>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I saw this piece of code which does not use a bracket or : before the if/else statement. I thought that every statement should start with { or :
What is the reason they do not use it here?
if (!$this->Article)
throw NotFoundException('Article');
// Set required permission.
$UserModel = new UserModel();
if ($this->Article->Status != ArticleModel::STATUS_PUBLISHED)
if (($this->Article->AttributionUserID == Gdn::Session()->UserID)
&& !$UserModel->CheckPermission($this->Article->AttributionUserID, 'Articles.Articles.Edit')
)
$this->Permission('Articles.Articles.View');
else
$this->Permission('Articles.Articles.Edit');
else
$this->Permission('Articles.Articles.View');
Please don't forget the edge case on calculating your code coverage with phpunit:
<?php
// Because it is "line based" and not statement base coverage
// one line will always have one coverage status
if (false) this_function_call_shows_up_as_covered();
// Due to how code coverage works internally these two lines are special.
// This line will show up as non executable
if (false)
// This line will show up as covered because it is actually the
// coverage of the if statement in the line above that gets shown here!
will_also_show_up_as_coveraged();
// To avoid this it is necessary that braces are used
if (false) {
this_call_will_never_show_up_as_covered();
}
?>
See https://phpunit.de/manual/current/en/code-coverage-analysis.html#code-coverage-analysis.edge-cases for more information.
Imo this is one reason why it is best practice to use always brackets, an other is, debugging such code you give as example is very annoying.
You use brackets to indicate to the interpreter where the if statement starts and stops. However, when the if statement only consists of one line, the brackets can be omitted and the interpreter conditionally executes (or not) the next line.
Whether or not this is a good practice is debatable.
If you have 2 or more operators in if statement always use brackets. If one operator, you can skip them.
But i suggest to always use brackets.
If the code that must to run in case the if statement returns true will have just a single line, you do not need the brackets. brackets in if statement are required just in case of more than one row of code inside it.
if the code between the "if" statement consists of one line you can get rid of bracket "{" but if the code of the "if" statement is consists of more than line you must use it
You can avoid the brackets when there is only one sentence to execute, or there is only one control statement... in this code:
if (!$this->Article)
throw NotFoundException('Article'); //Only one sentence
// Set required permission.
$UserModel = new UserModel();
if ($this->Article->Status != ArticleModel::STATUS_PUBLISHED)
//Insde there is only one if/else
if (($this->Article->AttributionUserID == Gdn::Session()->UserID)
&& !$UserModel->CheckPermission($this->Article->AttributionUserID, 'Articles.Articles.Edit')
)
//Inside there is only one sentence
$this->Permission('Articles.Articles.View');
else
//Else statement contains only one sentence
$this->Permission('Articles.Articles.Edit');
else
//Else statement contains only one sentence
$this->Permission('Articles.Articles.View');
In the first example if you want to execute 2 sentences, it must be enclosed in brackets like this:
if (!$this->Article)
{
$foo = true;
throw NotFoundException('Article');
}
Regards
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
what are the differences in die() and exit() in PHP?
I guess the main question is what is the difference between the 3 exactly?
What is the correct semantic usage for each one of these?
From what I see return false; can discontinue a function whereas die(); and exit(); will prevent any further code running at all.
Is this correct?
die() and exit() are precisely identical; they halt the entire PHP program and return to the OS. They're two different names for the same function.
return, on the other hand, ends a function call and returns to the caller. At the end of a program, return sets the status value that is returned to the OS; the program is going to exit no matter what.
According to docs PHP: exit Manual die() is an alias to exit() so they do the same function and that is to END the script.
The return statement ends a function and not the entire script, and returns the value that you choose.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is basic difference echo Vs print
The echo and print statements are nearly identical, but they have some differences.
For example, the print statement returns a value of 1 if it is successful
or a value of 0 if it is not successful, while the echo statement does
not return a value.
why print statement returns a value of 1 if it is successful. but echo doesn't. thank you
I've actually taken advantage of the return value of the print "function" in an ajax call:
return print json_encode($my_data);
It doesn't do anything at all with the return value, but it terminates the execution of the current script, which is a slightly prettier way of writing
echo json_encode($my_data);
die();
But as to why one returns something and the other doesn't.... probably isn't a terrible good reason for it. I reckon echo is ever so slightly (negligibly) faster because of it, whereas print has weird uses such as the aforementioned one.
As to what these other guys are saying about print() not being a language construct, but a function, I say to you, read the manual. It's a language construct too.