Reputation: 338
Is it possible to create a PHP function which can both display and return (Only one thing per time according how I called it)? Please look at the example.
Ex:
public function test_function(){
echo "Hello"; // echo or anything......
}
If I called it test_function()
it should display "Hello";
If I use it like $name = test_function();
$name
should be equal to "Hello".
Note : I know that passing another parameter and using if condition I can do this. I am looking for more quick way if there is something like that.
Upvotes: 0
Views: 51
Reputation: 6215
It's kinda possible with ob_start and ob_get_clean, like so:
function test_function(){
echo "Hello";
}
// Direct output
test_function();
echo PHP_EOL . '<br>-------<br>' . PHP_EOL;
// Catch output into variable
ob_start();
test_function();
$name = ob_get_clean();
echo "Name: " . $name;
Output:
Hello
-------
Name: Hello
See it running here.
I feel like mentioning: the answers suggesting to always return the value and print when needed are probably the way to go.
Upvotes: 0
Reputation: 19318
No, what you're suggesting isn't possible. There are a few alternatives as you're already aware but you can't do both. If you attempt to echo
and return
in the same function, you're going to get unexpected results when you attempt to use the function in a return context.
The best solution would be to return a value in your function and then echo.
function test_function() {
return 'Hello';
}
echo test_function();
Or
function test_function( $echo = false ) {
$value = 'Hello';
if ( $echo ) {
echo $value;
} else {
return $value;
}
}
Upvotes: 0
Reputation: 991
No. You should return 'Hello' and echo it if necessary.
function test_function() {
return 'Hello';
}
$foo = test_function(); // $foo = 'Hello'
echo test_function(); // Prints 'Hello'
Upvotes: 2