Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get return from echo

I'm working with some functions that echo output. But I need their return so I can use them in PHP.

This works (seemingly without a hitch) but I wonder, is there a better way?

    function getEcho( $function ) {
        $getEcho = '';
        ob_start();
        $function;
        $getEcho = ob_get_clean();
        return $getEcho;
    }

Example:

    //some echo function
    function myEcho() {
        echo '1';
    }

    //use getEcho to store echo as variable
    $myvar = getEcho(myEcho());      // '1'
like image 766
ryanve Avatar asked Sep 23 '11 14:09

ryanve


People also ask

Does echo have return value?

The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument.

What is echo return?

Unlike some other language constructs, echo does not have any return value, so it cannot be used in the context of an expression. echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign.

Is echo the same as return?

Echo is for display, while return is used to store a value, which may or may not be used for display or other use.

How do I return from a shell function?

return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of the last command executed within the function or script. N can only be a numeric value.


2 Answers

no, the only way i can think of to "catch" echo-statements it to use output-buffering like you already do. i'm using a very similar function in my code:

function return_echo($func) {
    ob_start();
    $func;
    return ob_get_clean();
}

it's just 2 lines shorter and does exactly the same.

like image 168
oezi Avatar answered Sep 28 '22 02:09

oezi


Your first code is correct. Can be shortened though.

  function getEcho($function) {
        ob_start();
        $function;
        return ob_get_clean();
    }
    echo getEcho($function);
like image 35
Mob Avatar answered Sep 28 '22 02:09

Mob