Can't understanding function's return and echo behaviour

Viewed 33

Why this echoing Hello Hello World World instead of Hello World Hello World

function a(){
    echo "Hello ";
    return "World ";
}
echo a().a();

Output:

Hello Hello World World
2 Answers

Because the function will echo twice before the string a().a() had been evaluated. The instruction echo a().a() says, run function a() twice, concatenate the output and echo the output. While concatenating the string to echo, the instruction echo "Hello " already ran twice. This is alike resolving math formulas, there are rules in which order the functions will execute.

Return function return value to calling function. while echo print the output when it is called. I have modified a code to present the testcase.

<?php

function a(){
    echo "Hello";
    return "World";
}
echo a();
echo a();
?>

output is like this

HelloWorldHelloWorld

In this case calling function return to main function control and print 'Hello World'. Then call the second call for a() function.

For your code. You are calling like this a().a(). In this case calling function returns value to location where it calls. In your case it returned value to a() then execute its body. After last return, controls came to main block code. Then echo the 'world'.

I hope this makes sense. Thanks

Related