In other words, can fn() know that it is being used as $var = fn(); rather than as fn();?
A use case would be to echo the return value in the latter case but to return it in the former.
Can this be done without passing a parameter to the function to declare which way it is being used?
Many PHP functions do this by passing a boolean value called $return which returns the value if $return is true, or prints the value if $return is false. A couple of examples are print_r() and highlight_file().
So your function would look like this:
function fn($return=false) {
if ($return) {
return 'blah';
} else {
echo 'blah';
}
}
Any other way will not be good programming style.
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