Search code examples
phpvariablesinclude

PHP - Isolate context with include


I want to include some PHP plugins, which should be able to modify a single variable ($input). The function I am using is the following:

$globalVariable = 'Hello, World!';

function plugin($type, $file, $input){

    if($type == 'foo'){

          return include('../foo-plugins/' . $file);

    }
    else{

          return include('../bar-plugins/' . $file);

    }

}

And the plugin file:

<?php

    global $globalVariable; // This should not work

    echo $file; // This should not work
    echo $type; // This should not work

    return 'Hello ' . $input; // This should work

?>

This post explains how to pass a variable, but does not solve my problem as all variables are passed on.

How can I set the context for the included file so it only has access to the single variable $input?

I am open to any alternative approaches, that don't necessarily use include or require. Any help would be much appreciated!


Solution

  • Use a self-invoking anonymous function to isolate its variable scope locally:

      $globalVariable = 'Hello, World!';
    
      function plugin($type, $file, $input){
            if($type == 'foo') {
                  return (function($file, $input) { 
                        return include('../foo-plugins/' . $file); 
                  })($file, $input);
                  
            } else {
                  return (function($file, $input) { 
                        return include('../bar-plugins/' . $file); 
                  })($file, $input);
            }
      }
    

    However, there's nothing you can do to prevent it from accessing global variables in any scope. If global variables are a concern, the code should be run in a separate PHP process, for example by invoking it from the command line or as a separate HTTP request.