I am trying to build a php class that will let me include other php “template” files to display. I want all of the variables that are in the scope that it is called from to be available in the included file. Here’s the catch, I want to pass off the actual including to a helper method to keep the code DRY. Here is what I have so far:
/* TemplateLoader.php */
class TemplateLoader {
public function foo() {
$var = "FOO!";
//Works
include 'template.php';
}
public function bar() {
$var = "BAR!";
//Doesn't work
$this->render("template");
}
private function render( $name ) {
include $name . '.php';
}
}
/* template.php */
<?php echo $var; ?>
My question is: How can I accomplish the behaviour of including the template directly in the original method while still using helper method to actually do the “heavy lifting”? I would really appreciate any help you can give!
This is what first came to my mind – I’m not sure I like it too much, but I’m not sure of a generic alternative. This captures all of the current variables with
get_defined_vars(), and passes them torender(), where they are theyextract()ed, and thus accessible by the included file.You could probably filter the return from
get_defined_vars()before you pass it torender(), but I should work.You could probably filter the return from
get_defined_vars()before you pass it torender(), but it should work.