echo $foo.$bar OR echo $foo,$bar

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

echo $foo.$bar OR echo $foo,$bar

Post by Ollie Saunders »

What is the difference between

Code: Select all

echo $foo.$bar
and

Code: Select all

echo $foo,$bar
There are a couple of differences that I know of.

Firstly is this one...

Code: Select all

class A {
	public function __toString() {
		return 'A';
	}
}

$foo = new A();
// __toString not called with dot
echo '123 '.$foo; // outputs "123 Object id #1"

echo "\n";

// __toString called using commas
echo '123 ',$foo; // outputs "123 A";
...which is an incentive to use commas.

And then there is this one...

Code: Select all

$a = 'cerial';
$b = 'milk';
$c = 'occasionally';
$msg = 'I '. $c .' eat '. $a .' with'. $b; // I occasionally eat cerial with milk
$msg = 'I ', $c ,' eat ', $a ,' with', $b; // Parse error: syntax error, unexpected ','
// to make the line above work i'd need to change all those commas to dots
...which is an incentive to use dot operators because you can easy and quickly change any echo to an assignment without having to go through and change all the operators you used.

Thing is I have a sneeky feeling that the comma is faster than the dot operator for output. Not being a Zend Engine programmer I can only spectulate but I have a feeling that this...

Code: Select all

echo $foo,$bar,$zim;
...is translated to...

Code: Select all

echo $foo;
echo $bar;
echo $zim;
...by the Zend Engine. Which may well be faster than this...

Code: Select all

echo $foo.$bar.$zim;
...which is probably translated to...

Code: Select all

$tmp = $foo.$bar.$zim; // involves processing
echo $tmp;
...by the Zend Engine.

Of course this is only a theory. I'm interested to know if I am correct.
santosj
Forum Contributor
Posts: 157
Joined: Sat Apr 29, 2006 7:06 pm

Post by santosj »

You are correct.

You can only use the comma for output $strings. echo is a langauage construct so what you are passing are parameters to echo.

You can't use it elsewhere to append strings to a string using a comma because it doesn't accept parameters.

Very good analysis!
Post Reply