'Prevent PHP leaking variables with include or require

I have unwanted arguments leaking into my template.php.

function template($template, $args) {
  $foo = $args['bar'];

  extract($args);

  include __DIR__ . '/' . $template . '.php';
}

In the template.php

  • $foo should not print out something because it's not extracted from $args.
  • $bar should print out something because it's extracted from $args. It does.
  • $template should not print out something because it's not extracted from $args.
<!DOCTYPE html>
<?= $foo; ?>
<?= $bar; ?>
<?= $template; ?>
</html>

In real life the HTML above is valid. Also, I have much more arguments in the template function.

How can I get around argument leaking? I could change scope by wrapping include in another function but then I still need $template which will then be passed to the template.php.

Any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source