Ash501 Ash501 - 1 year ago 101
PHP Question

Unset all variables in PHP script

Trying to unset automatically all variables in script.

Have tried this way:

echo '<br /> Variables in Script before unset(): <br />';
echo '<br /><br />';

// Creates string of comma-separated variables(*) for unset.
$all_vars = implode(', $', array_keys(get_defined_vars()));

echo '<br /><br />';
echo '<br />List Variables in Script: <br />';
echo $all_vars;

echo '<br /><br />';
echo '<br />Variables in Script after unset(): <br />';
echo '<br />';

Why does it not work?

Is there a better way to do this?

Thanks for helping!

(*) It's seems somewhat that it does not really create the variables, but a string that looks like variables...

Answer Source

Here ya go ->

$vars = array_keys(get_defined_vars());
for ($i = 0; $i < sizeOf($vars); $i++) {

And to clarify, implode returns "a string representation of all the array elements in the same order".

Unset requires the actual variable as a parameter, not just a string representation. Which is similiar to what get_defined_vars() returns (not the actual variable reference). So the code goes through the array of strings, and returns each as a reference using the extra $ in front - which unset can use.