Reputation: 739
I have basically 2 queries related this:
Consider the following PHP function in a class say xyz.php
function sendResponse(){
$car="Lambo";
echo $car;
}
function sendResponseTwo(){
$car="Lambo";
echo $car;
return $car;
}
function getResponse(){
//case 1:
$carName=$this->sendResponse();
//ABOVE WON'T WORK AS THE FUNCTION RETURNS NOTHING.
//case 2:
$carName=$this->sendResponseTwo();
//THIS WILL PRINT THE NAME OF CAR
}
In case 1, is there any way to get the echo values by calling the function in another function but without using return statement?
In case2, is there any way to stop the values printed by echo statement (I want only returned value)?
Upvotes: 0
Views: 590
Reputation: 15141
Answer to your both the question lies in output buffer(ob)
, Hope this will help you out in understanding. Here we are using three function ob_start()
will start output buffer and ob_end_clean()
will clean the output of buffer and ob_get_contents
will give you output as string which is echoed till now. This will help you better understand ob_get_contents
<?php
class x
{
function sendResponse()
{
$car = "Lambo1";
echo $car;
}
function sendResponseTwo()
{
$car = "Lambo2";
echo $car;
return $car;
}
function getResponse()
{
//case 1:
$carName = $this->sendResponse();
//ABOVE WON'T WORK AS THE FUNCTION RETURNS NOTHING.
//case 2:
$carName = $this->sendResponseTwo();
//THIS WILL PRINT THE NAME OF CAR
}
}
ob_start();//this will start output buffer
$obj= new x();
$obj->getResponse();
$string=ob_get_contents();//this will gather complete content of ob and store that in $string
ob_end_clean();//this will clean the output buffer
echo $string;
?>
Upvotes: 4
Reputation: 146450
You need to use output buffering:
ob_start();
$foo->sendResponse();
$response = ob_get_clean();
That's why it isn't a practical design in the first place. If you make the function always return the value it's trivial to do both things to your liking:
$response = $foo->sendResponse();
echo $foo->sendResponse();
<?=$foo->sendResponse()?>
(This last option is shared for illustration purposes and is not intended to open a flame war about short open tags.)
Upvotes: 1