Self-invoking functions in PHP

For a small PHP framework that I am refactoring, I needed to isolated variables from the framework in the output. Before, these variables could be called in the PHP templates, if you knew them (or guess them). Also $this was available because the templates are called inside a class.

This can potentially introduce security issues, because some sensitive information might get exposed. So I needed a better solution. The simplest being scoping. Any variables should only be available in the output scope.

In PHP this can by done with an anonymous self invoking function. Also known as an Immediately Invoked Function Expression (IIFE). For example in my use case I want to extract an array to variables and call a PHP template:

(function($template, $data) {
  extract($data);
  include $template;
})($template, $data);

This might be familiar to you if you write JavaScript code. This has been available since PHP 7.0.

Before, this was also possible by using call_user_func.

call_user_func(
  function ($template, $data) {
    extract($data);
    include $template;
  },
  $template,
  $data
);

This still leaves the passed variables available. Ideally, the template and data variables should not be available. But this is better than before. You could use unset($data) to get rid the $data variable.