PHP is a function that returns material that echoes other functions

let's say i have a set of features like

  • article() - displays the article
  • menu() - menu

etc.

Sometimes I may only need to get the output of such functions, and not print it on the screen. Therefore, instead of creating another set of functions that return type values get_article(), get_menu()etc., can I make one function that does this using output buffering and call_user_func?

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 to pass arguments $function_name. A function may require any number of arguments ...

+3
source share
6 answers

... , 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();
}

:

function foo($arg1, $arg2) { echo $arg1 . ':' . $arg2; }

$bar = get('foo', 'test', 'ing'); // $bar = 'test:ing'

.

+2

, , return echo - :

function article($output = false)
{
   // your code..........

   if ($output === true){
     echo $result;
   }
   else{
     return $result;
   }
}

, - , $output true :

article(true);

, $output:

article();
+3

call_user_func_array(), . , , , article() .

+3

article() menu(), $return, , false, , $return true, .

article($id, $return = false) 
{
  // ...
  if($return)
  {
    return $article;
  } else {
    echo $article;
  }
}
+3

, .

, , echo article();

+2

Yes it is possible. You may like it here .

+1
source

Source: https://habr.com/ru/post/1780898/


All Articles