Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of Operations for echo statements

Tags:

php

Here's my code:

<?php
    class Test_Class {
        public function Show() {
            return "Test_Class->Show() function";
        }
    }

    class Test_Class2 {
        public function Show() {
            echo "Test_Class2->Show() function";
        }
    }

    $var1 = new Test_Class();
    $var2 = new Test_Class2();

    echo "var1 :: " . $var1->Show() . "<br />";
    echo "var2 :: " . $var2->Show() . "<br />";
?>

Here's the output:

 var1 :: Test_Class->Show() function  
 Test_Class2->Show() functionvar2 :: 

You'll notice that the class that returns the string has the result appear where it normally would, whereas the class that echo's the string has the result appear before the echo statement that it is called in.

Now, I know that it's getting processed first, and that's why it's appearing first. But how does this look at a lower level?

It is something along the lines of:
.. parse
.. parse
.... Hey! And echo statement, let's parse it!
...... Hey! inside this echo statement that we're parsing is an object's method, let's parse that now
........ Inside this method there's an echo, so let's evaluate it (output's inner echo statement)
....We finished evaluating the echo statement (output outer echo statement)
.. parse
.. parse

Is that close?

Anyone know the "order of operations" when it comes to this?

like image 800
Tango Bravo Avatar asked Dec 17 '22 03:12

Tango Bravo


2 Answers

The string is concatenated during execution. The string must be built before it is echo'd.

If you want the parts to be echoed left to right, use commas:

echo "var1 :: ", $var1->Show() , "<br />";
echo "var2 :: " , $var2->Show() , "<br />";

/* output:

var1 :: Test_Class->Show() function
var2 :: Test_Class2->Show() function

*/
like image 188
webbiedave Avatar answered Jan 02 '23 16:01

webbiedave


It's nothing to do with parsing.

echo needs an argument; it cannot be invoked until that argument is known. In your second example, that argument is formed from two concatenation operations. These operations must be performed before the argument is known. Therefore, the arguments to these concatenation operations must be evaluated first. So $var2->Show() is evaluated before any concatenation is performed.

like image 23
Oliver Charlesworth Avatar answered Jan 02 '23 18:01

Oliver Charlesworth