Search code examples
phpsyntaxechoparentheseslanguage-construct

What is the difference between echo with braces and without braces, and why do both methods exist?


I think most of us that program in php learned to echo "string";. While common, I am wondering why we use this so different then any other function.

So why do we do:

echo "Some String";

Instead of

echo("Some String");

And why do both exist and behave differently? Is there any reference to why this choice was made?

People refer to the php docs stating that echo is a language construct and therefor is used differently. But in that case, since we can both use it as a construct aswell as functional: which is the preferred method? And why was it implemented both ways while it should only be a language construct?

The same as above pretty much counts for require, require_once, include and include_once. I can't find anything on the web explaining -why- these constructs were also implemented functional (and in the case of echo(), in a flawed way).


Solution

  • From php.net:

    echo is not actually a function (it is a language construct), so you are not required to use parentheses with it.

    if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.

    Example:

    <?php
    echo(1);        // < works fine
    echo(1, 2, 3);  // < Parse error: syntax error, unexpected ',' on line 3
    echo 1;         // < works fine
    echo 1, 2, 3;   // < works fine
    echo (1), (2), (3);   // < works fine
    

    Regarding your question "why do both methods exist?", using braces is not actually a "method". Those braces do not belong to echo, but to its argument. In PHP, almost any expression can be taken in braces. For example, ($a = 1); and $a = (1) are valid statements. So it's just an extra pair of braces. As well as in trim(($str));, where first pair of braces belongs to the function and the second pair - to its argument. So now you can tell that using echo with braces is as logical as using trim() with 2 pairs of braces.

    Everything said above is also applied to include, require, require_once and include_once, as well as other language constructs, but with some exceptions. For example, isset, although being a language construct, for some reason requires a pair of braces.

    Note that, as it's mentioned on the manual page for include, these language constructs have a return value. And because expressions like include 'fileA.php' == 'OK' are not obvious (according to operator precedence), when checking for the return value, you should use parentheses, either wrapping the entire expression: (include 'fileA.php') == 'OK' or the argument only: include('fileA.php') == 'OK'.