let's say I have a set of functions like,
article()
- outputs a articlemenu()
- a menu
and so on...
sometimes I may need to only get the output of such functions, not print it to the screen. So instead of creating another set of functions that return the values like get_article()
, get_menu()
etc., could I make a single function that does this, using output buffering and call_user_func
?
for eg.
function get($function_name){
ob_start();
call_user_func($function_name);
return ob_get_contents();
}
开发者_运维问答the problem in my code is that I don't know how could I pass the $function_name
's arguments. The function might need any number of arguments...
Why not create an optional argument to signal whether to return
or echo
output something like this:
function article($output = false)
{
// your code..........
if ($output === true){
echo $result;
}
else{
return $result;
}
}
Now if you want to echo something out of the same function, you should set $output
to true when calling the function like this:
article(true);
But if you want to just return the result of the function, you can call it without specifying $output
:
article();
You could use call_user_func_array()
, which would allow you to also pass an array of parameters. However it's probably better to make your article()
function return a string and echo it only if needed.
Or you could just modify article()
and menu()
to have a last optional parameter $return
which is a boolean that defaults to false
so when $return
is true
then you would return from the same function.
article($id, $return = false)
{
// ...
if($return)
{
return $article;
} else {
echo $article;
}
}
It's easy... Simply fetch the arguments using func_get_args
...
function get($function_name){
$arguments = func_get_args();
array_shift($arguments); // We need to remove the first arg ($function_name)
ob_start();
call_user_func_array($function_name, $arguments);
return ob_get_clean();
}
Usage:
function foo($arg1, $arg2) { echo $arg1 . ':' . $arg2; }
$bar = get('foo', 'test', 'ing'); // $bar = 'test:ing'
Note two things.
- This is ignoring the
return
of the called function. - I changed the ending function to
ob_get_clean()
since it deletes the created buffer. The code you had would make a new buffer for each call and not delete it (hence gradually slowing everything down as it needs to bubble all output up a large number of buffers)...
Or you could approach from the other way around, and write those functions in a way that they always return the values.
Then if you want to echo, you just say echo article();
Yes it's possible. You may like to look here.
精彩评论