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?
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local.
PHP has four types of variable scopes including local, global, static, and function parameters.
PHP has three types of variable scopes: Local variable. Global variable. Static variable.
Look at this:
$scope = function() { // It's very simple :) extract(func_get_arg(1)); require func_get_arg(0); }; $scope("RequiredFile.php", []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With