Search code examples
phpmodxmodx-revolution

How to Display output from snippet without using echo


The documentation on snippets in modx: http://rtfm.modx.com/display/revolution20/Snippets

Near the top of the doc it says: Note how we returned the code rather than echo'ed the content out. Never use echo in a Snippet - always return the output.

This doesn't display anything:

return $product_attribute $product_info[0][$column_name];

This does display:

echo $product_attribute $product_info[0][$column_name];

If I can't echo the content how do I get it to print in the html page?


Solution

  • It basically means that you can echo the returned value rather than echo the value in the function itself. In OOP programming, echoing (or printing) to the screen is strictly monitored.

    For example I have this function

    function testExample($var) {
        return $var*2;
    }
    

    So when I need to echo it, I just need to

    echo testExample(5);
    

    Instead of this (bad practice)

    function testExample($var) {
        echo $var*2;
    }
    

    The reason is that when you print value in the function, you can only use that function for printing the value, which isn't reusable at all. But by returning it, you can now use it for printing, or assigning to another variable or re-calculating on it.