Why does "exit" require parentheses?
If echo
开发者_StackOverflow中文版 can work withouth the parentheses why exit
can't?
They're both language constructs (T_ECHO and T_EXIT), but different kinds. You can use exit without parentheses, but not if you're passing a value. Another quirk is that echo requires you not to use parentheses if you pass more than one value:
php > echo 'foo', 'bar';
foobar
php > echo ('foo', 'bar');
PHP Parse error: syntax error, unexpected ',' in php shell code on line 1
If you're now thinking, "But that doesn't really explain why the design is inconsistent", welcome to PHP.
Simply because somebody programmed it as such, and nobody bothered to change it. Echo and exit do not share code, so they do not necessarily work the same way. There is no good reason for this.
Here is some code from PHP's parser. As you can see, echo and exit are followed by different expressions. Exit is followed by nothing, ()
or an expression between parenthesis. Echo is simply followed by an expression:
unticked_statement:
| T_ECHO echo_expr_list ';'
| T_EXIT exit_expr { ... }
...
exit_expr:
/* empty */ { ... }
| '(' ')' { ... }
| '(' expr ')' { ... }
;
echo_expr_list:
echo_expr_list ',' expr { ... }
| expr { ...; }
;
PHP got a lot of inspiration from C and (*nix) shells.
The echo
in shell does not require ()
's.
And the exit()
in C does (while return
doesn't).
In C
, return
is a language construct (return from a function call), while exit()
is a function performing the termination of a program.
PHP, as an interpreted language, was free to chose to consider exit
as a language construct, or a function with ()
. It is a language construct that can be used as exit;
or exit(x);
exit can, it just does not take a string!?
void exit ([ string $status ] ) void exit ([ int $status ] )
If status is a string, this function prints the status just before exiting.
If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
Example of using exit without:
if(defined('EXIT_END'))
{
exit;
}
Maybe because exit
is a function that echo
the first parameters and stop the script ?
精彩评论