Giving PHP include()'d files parent variable scope

后端 未结 2 1167
夕颜
夕颜 2021-01-05 00:19

Is there anyway to for an included file to be used in a parent scope to the one it was called in? The following example is simplified, but does the same job.

In esse

相关标签:
2条回答
  • 2021-01-05 01:07
    function include_use_scope($file, $defined_variables)
    {
        extract($defined_variables);
        include($file);
    }
    
    include_use_scope("file.php", get_defined_vars());
    

    get_defined_vars() gets ALL variables defined in the scope it is called in. extract() takes an array and defines them as local variables.

    extract(array("test"=>"hello"));
    echo $test; // hello
    
    $vars = get_defined_vars();
    echo $vars['test']; //hello
    

    Thus, the desired result is achieved. You might want to strip out the superglobals and stuff from the variables however, as overwriting them might be bad.

    Check out this comment for stripping the bad ones out.

    In order to get the reverse, you could do something like this:

    function include_use_scope($file, $defined_variables)
    {
        extract($defined_variables);
        return include($file);
    }
    
    extract(include_use_scope("file.php", get_defined_vars()));
    

    include.php

    // do stuff
    return get_defined_vars();
    

    But all in all, I don't think you are going to get the desired effect, as this was not how PHP was built.

    0 讨论(0)
  • 2021-01-05 01:19

    The only way I know how to is to use the superglobal array.

    main.php:

      $GLOBALS['myVar'] = 'something bar foo';
    
      $success = myPlugin('included.php');
    
      if($success)
      {
        echo $GLOBALS['myResult'];
      }
    

    included.php:

    <?php
      $GLOBALS['myResult'] = strlen($GLOBALS['myVar']);
    
    0 讨论(0)
提交回复
热议问题