Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've been able to come up with a solution using <code>eval</code> to inline the variable as a constant, thus preventing it from leaking.</p> <p>While using <code>eval</code> is definitely not a perfect solution, it does create a "perfectly clean" scope for the required file, something that PHP doesn't seem to be able to do natively.</p> <pre><code>$scope = function( $file, array $scope_array ) { extract( $scope_array ); unset( $scope_array ); eval( "unset( \$file ); require( '".str_replace( "'", "\\'", $file )."' );" ); }; $scope( "test.php", array() ); </code></pre> <p>EDIT:</p> <p>This technically isn't even a perfect solution as it creates a "shadow" over the <code>file</code> and <code>scope_array</code> variables, preventing them from being passed into the scope naturally.</p> <p>EDIT2:</p> <p>I could resist trying to write a shadow free solution. The executed code should have no access to <code>$this</code>, global or local variables from previous scopes, unless directly passed in.</p> <pre><code>$scope = function( $file, array $scope_array ) { $clear_globals = function( Closure $closure ) { $old_globals = $GLOBALS; $GLOBALS = array(); $closure(); $GLOBALS = $old_globals; }; $clear_globals( function() use ( $file, $scope_array ) { //remove the only variable that will leak from the scope $eval_code = "unset( \$eval_code );"; //we must sort the var name array so that assignments happens in order //that forces $var = $_var before $_var = $__var; $scope_key_array = array_keys( $scope_array ); rsort( $scope_key_array ); //build variable scope reassignment foreach( $scope_key_array as $var_name ) { $var_name = str_replace( "'", "\\'", $var_name ); $eval_code .= "\${'$var_name'} = \${'_{$var_name}'};"; $eval_code .= "unset( \${'_{$var_name}'} );"; } unset( $var_name ); //extract scope into _* variable namespace extract( $scope_array, EXTR_PREFIX_ALL, "" ); unset( $scope_array ); //add file require with inlined filename $eval_code .= "require( '".str_replace( "'", "\\'", $file )."' );"; unset( $file ); eval( $eval_code ); } ); }; $scope( "test.php", array() ); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload