Reputation: 3
<?php
function dosomething(){
echo "do\n";
}
$temp="test".dosomething();
echo $temp;
?>
expected result:testdo
but actual result is: do
test%
I know how to change the code to get the expected result. But what i doubt is why the code prints result like this. Can someone explain it?Thanks!
Upvotes: 0
Views: 56
Reputation: 3425
Try this:
Use return in the calling function. Doing that you will get the string where the function is being called. So function is being replaced by string and 2 strings will then con cat.
-
Thanks
Upvotes: 0
Reputation: 138
I'm not sure why people are getting down voted. Their answers are right.
Upvotes: 0
Reputation: 195
Use a return statement instead of echo
function dosomething(){
return "do\n";
}
Upvotes: 1
Reputation: 22656
dosomething
is echoing to the screen. Since this runs first "do\n" is printed.
dosomething
also doesn't return anything so the second echo is equivalent to echo "test";
In order to use the result of the call you should return it:
function dosomething(){
return "do\n";
}
Which will behave as you expect.
To clarify. In order to work out what $temp
is the function must be run first which prints out "do\n" first.
Upvotes: 3