Why does exit require parentheses?

If echo can work with parentheses, why can't exit ?

+4
source share
5 answers

They are language constructs (T_ECHO and T_EXIT), but different. You can use exit without parentheses, but not if you pass a value. Another feature is that the 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 now think, β€œBut that doesn’t really explain why the design is incompatible,” welcome to PHP.

+11
source

Just because someone programmed it as such, and no one bothered to change it. Echo and exit do not use code, so they do not necessarily work the same. There is no good reason for this.

Here is some code from the PHP parser. As you can see, different expressions follow the echo and exit. The output is not followed by anything () or an expression between the brackets. The echo simply follows the expression:

 unticked_statement: | T_ECHO echo_expr_list ';' | T_EXIT exit_expr { ... } ... exit_expr: /* empty */ { ... } | '(' ')' { ... } | '(' expr ')' { ... } ; echo_expr_list: echo_expr_list ',' expr { ... } | expr { ...; } ; 
+5
source

PHP got a lot of inspiration from C and (* nix) shells.

In the shell, echo not required () . And exit() in C (while return not).

In C , return is a language construct (return from a function call), and exit() is a function that completes a program.

PHP, as an interpreted language, was free to choose exit as a language construct or function with () . This is a language construct that can be used as exit; or exit(x);

+3
source

exit can, it just doesn't accept the string !?

void exit ([string $ status]) void exit ([int $ status])


If the status is a string, this function prints the status before exiting.

If the status is an integer, this value will be used as the exit status and will not be printed. Exit statuses must be in the range of 0 to 254, exit status 255 is reserved by PHP and should not be used. State 0 is used to complete the program successfully.

An example of using output without:

 if(defined('EXIT_END')) { exit; } 
0
source

Perhaps because exit is a function that echo contains the first parameters and stops the script?

-1
source

All Articles