Have you ever working on some PHP software that had functions that echo’ed and you want them to return so you can echo later or pass the data to something else? I found a nice way of presenting the solution. All of the php functions that start with ob_ such as ob_start() allow you to do this, but it takes several lines of code, and doesn’t seem very clean. I’ve put these into a a function that can be used as follows:
/**
* Captures output from a function
*
* @param $callback is the name of the function
* @return the output of the function
*/
function capture($callback)
{
$args = func_get_args();
array_shift($args);
ob_start();
if (count($args))
call_user_func_array($callback, $args);
else
call_user_func($callback);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
$sidebar = capture('get_sidebar');
// or if it was a function you needed to pass arguments into
$title = 'Test';
$author = 'Nate Nuzum';
$header = capture('get_header', $title, $author);
// works in the newer version of php 5
$sidebar = capture(function()
{
get_sidebar();
});
function get_sidebar()
{
echo 'hello';
}
function get_header($title, $author)
{
echo "{$title} {$author}";
}