Viewed   102 times

I have a simple PHP function that outputs HTML.

<?php
function get_header() {
?>
<div id="header">
  <div class="page-width">
  <!-- And a lot more HTML after this line. -->
<?php
}
?>

So, when I call get_header(), the function outputs the HTML.

What is the simplest option to tweak this function to return the HTML as a string? Do I need to create a wrapper around this function? In other words, I'd like to be able to do e.g. var html_string = get_header_wrapper(), where html_string contains all the HTML above.

One thing I could think of is to duplicate the function and make it return a string. However, that would be so inefficient because it introduces a lot of code duplicate.

<?php
function get_header_wrapper() {
  var ret = <<<EOD
  <div id="header">
    <div class="page-width">
    <!-- And a lot more HTML after this line. -->
  ...
  EOD;

  return ret;
}
?>

 Answers

4

You can make use of output bufferingDocs to get the output of that function:

ob_start();
get_header();
$html = ob_get_clean();

If you need that more than once, you can wrap it into a function of it's own:

/**
 * call a function and return it's output as string.
 * 
 * @param callback $function
 * @param array $arguments (optional)
 * @param var $return (optional) the return value of the callback
 * @return string function output
 */
function ob_get_call($function, array $arguments = array(), &$return = NULL)
{
    ob_start();
    $return = call_user_func_array($function, $arguments);
    $buffer = ob_get_clean();
    return $buffer;
}

Usage:

$html = ob_get_call('get_header');

As the answer is that popular today, here is another function to get the output of an include:

/**
 * include a file and return it's output as string.
 * 
 * @param string $file
 * @param array $variables (optional) keys as variable names and values as variable values
 * @param var $includeReturn (optional) the return value of the include
 * @return string function output
 */
function ob_get_include($file, array $variables = array(), &$includeReturn = NULL)
{
    $includeFilename = $file;
    unset($file);
    extract($variables);
    unset($variables);
    ob_start();
    $includeReturn = include($includeFilename);
    return ob_get_clean();
}

Usage:

include.php:

<div class="greeting">
    Hello <em><?php echo htmlspecialchars($name); ?></em>!
</div>

Using:

$variables = array(
    'name' => 'Marianne',
);
$html = ob_get_include('include.php', $vars);

Related:

  • Answer to *Load result of php code instead of the code as a string
  • Answer to Is include()/require() with “side effects” a bad practice?
Wednesday, September 7, 2022
4
function text($var) 

{

    if ( ! $var) {
        return;
    }
    do_something();

}

$var = text('');

echo gettype($var);
echo is_bool($var) ? "true" : "false";
echo is_string($var) ? "true" : "false";
echo is_null($var) ? "true" : "false";

returns:

NULL false false true

Thursday, November 3, 2022
 
2

Cracks knuckles

Technically the syntax is "correct" (it won't generate a fatal error) but the semantics of PHP render it effectively meaningless in its current form. Let's look at a few things first, namely how PHP handles the assignment of named functions to variables:

php > echo shell_exec("php -v");
PHP 5.4.16 (cli) (built: Oct 30 2018 19:30:51)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

php > function speak($arg) {echo "{$arg}n";}
php > function give($arg) {return $arg;}
php > $speak = speak(4);
4
php > $give = give(4);
php > var_dump($speak);
NULL
php > var_dump($give);
int(4)

The function itself is executed upon assignment and its return value (NULL or otherwise) is assigned to the variable. Since we're only assigning the return value of a function's execution, trying to use this variable as a function name has no use:

php > $speak(4);
php > $give(4);
php >

Let's contrast this to the assignment of an anonymous function (a.k.a. a 'Closure'):

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php { };
php > var_dump($checkName);
object(Closure)#1 (2) {
  ["static"]=>
  array(2) {
    ["min"]=>
    int(1)
    ["max"]=>
    int(6)
  }
  ["parameter"]=>
  array(1) {
    ["$value"]=>
    string(10) "<required>"
  }
}

Unlike some other languages, a closure is represented in PHP by an actual Object. Variables inside the 'use' clause are imported at the time the Closure was created; function parameters (i.e. $value) have their values captured when the Closure is called (hence why we see it noted as a required parameter and not a static value). The semantics of references within Closures aren't worth considering right now but if you want further reading, goat's answer to this question is a great start.

The major takeaway here is that the Closure's assignment to $checkName did not execute the Closure itself. Instead, $checkName becomes a sort of "alias" we can use to reference this function by name:

php > $checkName("hello ");
value: hello 
min: 1
max: 6
php >

Given how loose PHP is about the number of function parameters passed, a zero-parameter execution returns expected results:

php > $checkName();
value:
min: 1
max: 6
php >

Now let's take it another level deeper and define a function within a function:

php > function myOuterFunc($arg) {
php {   function myInnerFunc($arg){
php {     echo "{$arg}n";
php {   }
php { }
php > $myVal = myOuterFunc("Hello ");
php > var_dump($myVal);
NULL
php >

By now this result should make sense. Functions do not execute unless explicitly called; just because we call myOuterFunc doesn't mean we execute any function code defined inside of it. That's not to say that we couldn't:

php > function myOuterFunc($arg) {
php {   function myInnerFunc($arg){
php {     echo "{$arg}n";
php {   }
php {   myInnerFunc($arg);
php { }
php > $myVal = myOuterFunc("Hello ");
Hello 
php > var_dump($myVal);
NULL
php >

Which brings us back around to what is essentially your question: what about a named function inside of a Closure? Given what we've now discovered about function execution, we can generate a series of very predictable examples:

$min = 1; $max = 6;
$checkName = function ($value) use ($min, $max) {
  function question(){echo "How are youn";}
  echo "value: {$value}n";
  echo "min: {$min}n";
  echo "max: {$max}n";
};
php > $checkName("Hello ");
value: Hello 
min: 1
max: 6
php >

As expected, the named function's code inside the Closure is not executed because we have not explicitly called it.

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   function question(){echo "How are youn";}
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php {   question();
php { };
php > $checkName("Hello ");
value: Hello 
min: 1
max: 6
How are you
php >

Explicitly calling the inner function works just fine, provided we define that function before we call it:

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php {   question();
php {   function question(){echo "How are youn";}
php { };
php > $checkName("Hello ");
value: Hello 
min: 1
max: 6
php >

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php {   function question(){echo "How are youn";}
php {   question();
php { };
php > $checkName("Hello ");
value: Hello 
min: 1
max: 6
How are you
php >

So to the point of your questions then:

  1. Yes it's legal and what you're attempting is possible but semantically meaningless in its current form.

  2. Any named functions inside the Closure definitely do not reside in the global namespace, they are within the scope of their defining Closure. FWIW, the term "members" typically refers to class variables (usually called "properties" in PHP). While Closures are an Object and let you duplicate the functionality of instance variables found within classes, they should not be confused or construed with classes in any way.

3/4) Not how you're trying to use it, no. Nothing outside of the Closure has any concept of the functions inside; if in calling your Closure code, said code performs operations using the inner functions, then they will see the light of day. But there is no immediate way to reference those inner functions as if they were defined outside of the Closure's scope.

In other words, the only way you'll get those inner functions to execute is if a) that code is specifically executed by the Closure's code and b) you execute said Closure code.

Hope this helps.

Tuesday, December 20, 2022
 
2

There is no better way I know of. Bash knows only status codes (integers) and strings written to the stdout.

Saturday, October 1, 2022
5

You should simply store the return value in a variable:

$deliveryPrice = getDeliveryPrice(12);
echo $deliveryPrice; // will print 20

The $deliveryPrice variable above is a different variable than the $deliveryPrice inside the function. The latter is not visible outside the function because of variable scope.

Sunday, September 18, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :