I have the following class:
abstract class TheView
{
public $template = NULL;
public $variables = array();
public function set($name, $value)
{
$this->variables[$name] = $value;
}
public function display()
{
include($this->template);
}
}
The template file is a simple PHP file:
<?php
echo $Message;
?>
How can I make all the variables in TheView::$variables available in the template (the key of each item should be the name of the variable).
I’ve already tried to add all variables to $GLOBALS but that didn’t work (and I think it’s a bad idea).
I always end up doing this:
Note the anonymous function and
func_get_arg()call; I use them to prevent$thisand other variable “pollution” from being passed into the template. You can unset$databefore the inclusion too.If you want
$thisavailable though, justextract()andinclude()directly from the method.So you can:
With
path/to/view.php:If you want the View object passed, but not from the scope of the
render()method, alter it as follows:$viewwill be the instance of the View object. It will be available in the template, but will expose only public members, as it is from outside the scope of therender()method (preserving encapsulation of private/protected members)