Have you seen PHP functions used without parentheses, such as echo
or include
? That’s because these aren’t really functions. They are a short list of entities called language constructs.
Below is a list of PHP language constructs. Half of these can be used with or without parentheses. It is entirely optional and that is why you have seen it done both ways.
Using parentheses will make your code slightly more consistent and readable. It would also be slightly less confusing to those who read it. After all, you ended up on this article as well!
According to PHP.net, not using parentheses will make your code slightly faster, because it means PHP has to do a little less work. In testing, however, this is not the case. Consider one of my speed tests:
<?php $time_start = microtime(true); for($i=0;$i<250000;$i++){ // try this include with or without () $y = include "test.txt"; } $time_end = microtime(true); echo $time_end - $time_start; ?> |
Over a loop with a quarter-million iterations, the include
statement with and without parenthesis would execute at the same speed of 27-28 seconds. In a second test using twenty five million iterations, a blank echo
would take 4.2 seconds either way. Therefore, the decision is easy.
Solid Statement: Always use parentheses with language constructs. It makes your code more readable and consistent, without sacrificing speed.
List of PHP Language Constructs
Parentheses Optional |
Parentheses Required |
|
|
|
Came across this post while researching something related.
First, the list of parens required is wrong.
Second, not all of those are language constructs, some of them are functions.
Third, the “Solid Statement” is not best practice.
PHP experts agree that language constructs should not use parens since it makes them look like functions, which they are not.
It is actually *more* confusing to use parens with language constructs.
Furthermore, C and C++ and Perl, after which PHP is modeled, don’t use parens either for language constructs.
Sorry to break it to you…
1. All 14 items in the list are language constructs and not functions. Feel free to look up every one of them at http://php.net/manual.
2. Those listed with required parentheses are correct, with only 1 circumstance allowing you to leave them out –
die
orexit
the script without a message. You cannot use the syntaxdie "message"
orexit "message"
, so you should use it for consistency.3. I AM a PHP expert and this isn’t C, Java, or Perl. This is PHP, where half of the language constructs require you to use parenthesis. Therefore, your suggestion is to use it some of the time and not use it others. That is inconsistent and leaves people wondering when they need them and when they don’t. I solidly stated the clear answer when I wrote this article and still stand by it 100%.