1

I'm trying to refactor some code and there are templates that use global variables. require and include inside of a function only uses local scope, so is there a way to "require global"?

Right now, we have quite a few lines of code duplicated across all router files like this. The statements that this issue refers to:

require 'header.php';
require $template;
require 'footer.php';

These statements are found in the global scope. I'm trying to refactor these into a method inside a class like this:

class Foo {

    /**
     * Template file path
     * @var string
     */
    protected $template;

    public function outputHTMLTemplate() {
        header("Content-Type: text/html; charset=utf-8");
        require 'header.php';
        if (file_exists($this->template)) {
            require $this->template;
        }
        require 'footer.php';
    }

}

Suppose I have template.php, inside the template there are superglobals and global variables like this:

<h1>Hello <?= $_SESSION['username']; ?></h1>
<ul>
<?php
foreach ($globalVariable1 as $item) {
    echo "<li>$item</li>";
}
?>
</ul>

This is a simplified example, in the actual templates there could be quite a few global variables.

How should I go about moving the output code to a method?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156

2 Answers2

0

You could try using the extract php function. It will make all global variables available to the included file, just as if it was included in global scope.

<?php

$myGlobal = "test";

class Foo {

    /**
     * Template file path
     * @var string
     */
    protected $template;

    public function outputHTMLTemplate() {
         extract($GLOBALS);

         header("Content-Type: text/html; charset=utf-8");
         require 'header.php';
         if (file_exists($this->template)) {
             echo $myGlobal; // Prints "test"
             require $this->template;
         }
         require 'footer.php';
    }

}

$x = new Foo();
$x->outputHTMLTemplate();
Christian
  • 1,663
  • 19
  • 33
0

Superglobals will already be available. For other variables it's a little extra work, but a normal approach would be something like:

protected $data;
protected $template;

public function outputHTMLTemplate() {
     header("Content-Type: text/html; charset=utf-8");
     require 'header.php';
     if (file_exists($this->template)) {
         extract($this->data);
         require $this->template;
     }
     require 'footer.php';
}

public function setData($var, $val) {
    $this->data[$var] = $val;
}

$foo->setData('globalVariable1', $globalVariable1);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87