Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flush out all variables in php

Tags:

php

Is it possible to flush all variables in running page or can I get the all variable list which are already stored some data?

like image 877
Subhojit Mukherjee Avatar asked Dec 17 '25 16:12

Subhojit Mukherjee


2 Answers

Have a look at

get_defined_vars()

http://php.net/manual/en/function.get-defined-vars.php

If you want to print the full list of variables (including superglobals) just:

print_r(array_keys(get_defined_vars()));

Also, as some others have mentioned in comments, if you need this you way want to think about reducing the number of variables you're using. The three easiest ways to do this (in my experience) are to overwrite variables when appropriate, for instance (silly example):

$subtotal = 0;
for($i=0;$i<10;$i++){
   $subtotal = $subtotal + $i;
}
$total = $subtotal;

can be better written:

for($total=0;$total <10;$total++){
  //nothing, I'm just itterating
}

which allows you to have one a single variable rather than three (this will also reduce memory allocation). The other useful trick is to store related variables in array or objects. For instance, instead of:

$number_of_widgets = 10;
$size_of_widgets = '120cm';
$cost_of_widgets = '$10.00';
$number_of_cogs = 13;
$size_of_cogs = '40cm';
$cost_of_cogs = '$3.00';

it is much easier to keep track of (and help prevent accidental variable-overwriting) if you add them to associative arrays:

$widgets = array('quantity'=>10,'size'=>'120cm','cost'=>'$10.00');
$cogs = array('quantity'=>13,'size'=>'400cm','cost'=>'$3.00');

And finally, if your variable isn't going to be modified (and isn't an array) just use a defined constant:

define('MAX_WIDGET_QUANTITY',300);

This has the advantage that (a) it's really easy to manage in the future if you ever want to change these contraints, (b) it's automatically available at the global scope, and (c) it makes code easier to read, as it is apparent that it is supposed to be a fixed value and should not be modified.

There are other tricks as well, but these will usually get you a long way towards variable manageability.

like image 164
Ben D Avatar answered Dec 19 '25 04:12

Ben D


You can use get_defined_vars to do this.

From the linked page:

This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.

So this would give you the names of all the variables:

array_keys(get_defined_vars())
like image 43
Andy Avatar answered Dec 19 '25 05:12

Andy



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!