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?