Ashitaka
Ashitaka

Reputation: 3

php concatenation operator use when operand is a function

<?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

Answers (5)

Anand Solanki
Anand Solanki

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

Sparatan117
Sparatan117

Reputation: 138

I'm not sure why people are getting down voted. Their answers are right.

http://codepad.org/nagGXY99

Upvotes: 0

guikk
guikk

Reputation: 195

Use a return statement instead of echo

function dosomething(){
    return "do\n";
}

Upvotes: 1

Jim
Jim

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

Alexey Dmitriev
Alexey Dmitriev

Reputation: 163

Use return.

function dosomething(){
return "do\n"; }

Upvotes: 1

Related Questions