Is it possible in PHP to require
an arbitrary file without leaking any variables from the current scope into the required file's variable namespace or polluting the global variable scope?
I'm wanting to do lightweight templating with PHP files and was wondering for purity sake if it was possible to load a template file without any variables in it's scope but the intended ones.
I have setup a test that I would like a solution to pass. It should beable to require RequiredFile.php
and have it return Success, no leaking variables.
.
RequiredFile.php:
<?php
print array() === get_defined_vars()
? "Success, no leaking variables."
: "Failed, leaked variables: ".implode(", ",array_keys(get_defined_vars()));
?>
The closest I've gotten was using a closure, but it still returns Failed, leaked variables: _file
.
$scope = function( $_file, array $scope_variables ) {
extract( $scope_variables ); unset( $scope_variables );
//No way to prevent $_file from leaking since it's used in the require call
require( $_file );
};
$scope( "RequiredFile.php", array() );
Any ideas?
Look at this:
$scope = function() {
// It's very simple :)
extract(func_get_arg(1));
require func_get_arg(0);
};
$scope("RequiredFile.php", []);