PHP - 使用 include 隔离上下文

问题描述 投票:0回答:2

我想包含一些 PHP 插件,它们应该能够修改单个变量(

$input
)。我正在使用的功能如下:

$globalVariable = 'Hello, World!';

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

    if($type == 'foo'){

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

    }
    else{

          return include('../bar-plugins/' . $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

?>

这篇post解释了如何传递变量,但并没有解决我的问题,因为所有变量都被传递了。

如何设置包含文件的上下文,使其只能访问单个变量

$input

我对任何替代方法持开放态度,这些方法不一定使用 include 或 require。任何帮助将不胜感激!

php variables include
2个回答
1
投票

使用自调用匿名函数在本地隔离其变量作用域:

  $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);
        }
  }

但是,您无法阻止它访问任何范围内的全局变量。如果需要考虑全局变量,则代码应在单独的 PHP 进程中运行,例如从命令行调用它或作为单独的 HTTP 请求。


1
投票

还有一个不完美的解决方案:

$globalVariable = 'Hello, World!';

  function plugin($type, $file, $input){
        $inst94a3u76bc0 = new \stdClass();
        $inst94a3u76bc0->file = $file;
        $inst94a3u76bc0->type = $type;

        unset($type, $file); // Unset them to avoid variable pollution.

        if($inst94a3u76bc0->type == 'foo') {
              return include('../foo-plugins/' . $inst94a3u76bc0->file); 
              
        } else {
              return include('../bar-plugins/' . $inst94a3u76bc0->file); 
        }
  }

但是,这并不能隔离全局声明。

© www.soinside.com 2019 - 2024. All rights reserved.