Search code examples
phpfunctionvariablesoperator-precedence

function and variable execution precedence


I tried to print a simple variable concatenated with a function call, and this is what I got!

 <?php 
 $hello = "Hello ";
 function test(){
   echo "This is a function!! ";
 }
 echo $hello.test();
 ?>

Here the echo prints the variable hello concatenated by the function call, so that should make the output Hello This is a function!!, instead the output is This is a function!! Hello.

  • How does this work and can someone explain this behaviour?

Solution

  • test() is a void function (it returns nothing) so there is no string for echo to immediately echo and the precedence of the function call is higher than the dot so will be evaluated first and does it's own echo before getting back to do the string join.

    return "This is a function!! ";

    .. will work with your original dot joined format (as others have pointed out).

    Alternatively, changing the echo line to:

    echo $hello, test();

    .. also works. $hello is a string and gets echoed, ~then~ test() gets evaluated.