Just for fun I did try what you where doing and I have to say that was some weird result, I can see where it could be confusing. The way I look at it is this, if you don’t need a value back and just want to display it to the screen the use echo, otherwise use return to assign it to a variable. The to be honest in my opinion it’s easier to use return and assign it to a variable.
Unless you have a specific reason not to do it this way, you should always return a value in a function. This is even more important when dealing with class methods. Now, you can output instead if you have reason, I will build forms inside of functions and call them when needed, because using that in a return makes it more complicated.
If you have ever used C or Java, you know that to make a function you have to say, for example
[php]void win() {
//You won!
}[/php]
The void on the beginning means that the function doesn’t return anything. If you wanted it to, you would say String win() {} for example. Now to PHP:
[php]
//Echo method
function win() {
echo ‘You won! Congratulations!’;
}
win();
//Return method
function win() {
return ‘You won! Congratulations!’;
}
echo win();
[/php]
As you can see, return uses slightly more code. But what is the point of it? Why would you use more code? As with many things, it is for forward compatiblity (I think thats what its called :)). Basically, you want to be able to use this in the future. What if, in the future, you want to lowercase the entire thing. Why would you do that, I don’t know, but there are real world implications. Here is how you would do it:
[php]
//Echo method
function win($lower = false) {
if($lower) {
echo ‘You won! Congratulations!’;
} else {
echo strtolower(‘You won! Congratulations!’;
}
win();
win(true);
//Return method
function win() {
return ‘You won! Congratulations!’;
}
echo win();
echo strtolower(win());
[/php]
Hope this helps!
I believe in PHP, functions are performed before any type of output. If you have an echo inside of a function, the echo inside of that function will get processed before any type of echo outside of the function due to functions getting processed first. Kind of like (2+3) / 2: (2+3) will be performed before the / 2. You would use the RETURN keyword to throw the value back outside of the function. The value 13 will be sent back for the echo to echo it out later.
Take a look at this:
[php]if(isValid())[/php]
The function gets performed first then it’s taken in by the IF statement; this is the same as the ECHO. This is why you get 139 + 4. Hope this explains things.