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'
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.
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.
Echo is for display, while return is used to store a value, which may or may not be used for display or other use.
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.
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.
Your first code is correct. Can be shortened though.
function getEcho($function) {
ob_start();
$function;
return ob_get_clean();
}
echo getEcho($function);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With