Andrew
Andrew

Reputation: 2154

Accessing variables in included file through helper method in PHP

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!

Upvotes: 1

Views: 120

Answers (1)

nickb
nickb

Reputation: 59699

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 to render(), where they are they extract()ed, and thus accessible by the included file.

You could probably filter the return from get_defined_vars() before you pass it to render(), but I should work.

public function bar() {
    $var = "BAR!";
    $this->render("template", get_defined_vars());
}

private function render( $name, &$vars) {
    extract( $vars);
    include $name . '.php';
}

You could probably filter the return from get_defined_vars() before you pass it to render(), but it should work.

Upvotes: 2

Related Questions