The question is in the title.
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:
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?
Edit: I see my question being flooded with both downvotes and upvotes. Please be constructive when voting either way.
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?
Edit 2: 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).
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 (as of PHP 5.4.14
):
<?php
header('Content-Type: text/plain');
echo(1); // < works fine
echo(1, 2, 3); // < Parse error: syntax error, unexpected ',' on line 6
echo 1; // < works fine
echo 1, 2, 3; // < works fine
?>
UPDv1:
Note: Because this is a language construct and not a function, it cannot be called using variable functions.
<?php
header('Content-Type: text/plain');
$print = 'print_r';
$print(1); // < works fine
$echo = 'echo';
$echo(1); // < Fatal error: Call to undefined function echo() on line 8
?>
UPDv2:
As of include
(same applies to require
, require_once
and include_once
), it might have a return value. For example:
fileA.php:
<?php return 1; ?>
fileB.php:
<?php return 'abc'; ?>
Test:
<?php
header('Content-Type: text/plain');
echo (include 'fileA.php'); // one way
echo PHP_EOL;
echo include('fileB.php'); // another way
?>
Shows:
1
abc
It was mentioned on php.net in examples #4 and #5.
Because expressions like include 'fileA.php' == 'OK'
are not obvious (according to operator precedence), you should enclose them in parentheses, or use "function-like" approach: (include 'fileA.php') == 'OK'
or include('fileA.php') == 'OK'
.
From the PHP docs
echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses
It's not a funcion, hence no parenthesis
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With