Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the efficient way to create a safe variable scope in a PHP file that is beeing included?

Tags:

scope

include

php

Here is a very simplified example of the setup:

includes/form.php

$secret_var = 'Mind blowing secret';
return '<form></form>';

page.php

echo include('includes/form.php'); // Notice the unusual way of including
echo $secret_var;

Result

<form></form>
Mind blowing secret

As you see, I'm not returning $secret_var, but its still exposed!

What is the most efficient way to create a scope for all variables within that includes/form.php, so that they are automatically unset by PHP?

Ofcourse I know I can run unset($secret_var);, but there are lots of forms, with many variables each and different developers constantly changing them. On a long term this method will mean basically a 100% chance to bugs. I need to do it somehow automatic (like variables within a function), but in this case without use of a named function (a file may be included more than once). It is also the highest priority to leave the code inside page.php unmodified, as this will mean a lot of changes system wide.

Maybe I could use an Anonymous function or something? Would be nice not to harm the performance...

like image 455
Slava Avatar asked Dec 14 '25 16:12

Slava


1 Answers

Instead of

echo include('includes/form.php'); // Notice the unusual way of including
echo $secret_var;

use

echo call_user_func(function(){
    // secret var's scope is only valid in this block...
    // while the return '<form></form>'; is... returned.
    include('includes/form.php');
});
echo $secret_var;

and see how it goes.

PS: Don't echo include. It means echo bool;, not the return in it.

PPS: And you're not using includes properly, as they're meant to... but I'm not even gonna start with that.

like image 143
CodeAngry Avatar answered Dec 17 '25 07:12

CodeAngry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!