Published

Wed 11 Dec 2013 @ 01:31 PM

←Home

Preserving PHP Variables

I was working on a little PHP script for a web site I'm developing. I wanted to briefly use a global variable, but I didn't want to risk overwriting any existing value in that variable. Normally one mitigates this problem by picking an obscure variable name that is unlikely to be in use anywhere else in the program, but that's not an ideal solution (to my way of thinking).

The idea I came up with (and maybe this is common knowledge, but I didn't find it online) was to convert the variable to an array, where one element of the array would be the original value of the variable, and another element would be the temporary value I needed. So I wrote some code like this:

$state = array('old' => $state, 'new' => some-other-value);
// do some stuff with state here
$state = $state['old'];

This code suffers from the problem that, if the $state variable is unset, an error report might be written to the output stream. Refining it a bit further by using PHP's isset function:

$state = array('set' => isset($state),
               'old' => isset($state) ? $state : NULL,
               'new' => some-other-value);
// do some stuff with state here
if ($state['set'])
    $state = $state['old'];
else
    unset($state);

This code is much better. The one "flaw" it has (at least in the opinion of my own unique brand of OCD) is that the isset function does not differentiate between a variable set to NULL and an unset variable. It does prevent any error messages from being written to the output, but after the last line, the program may be in a slightly different state than it started. This would happen if $state was set to NULL prior to this block of code. After the block, it will be unset, possibly resulting in error messages if later code assumes that $state is set to NULL.

I racked my brain for a little bit trying to resolve this "problem" (not that it is a huge problem) and came up with this final solution:

$state = array('set' => array_key_exists('state', $GLOBALS),
               'old' => array_key_exists('state', $GLOBALS) ? $state : NULL,
               'new' => some-other-value);
// do some stuff with state here
if ($state['set'])
    $state = $state['old'];
else
    unset($state);

This code prevents any error messages from being generated and it leaves $state exactly as we found it (either unset, set to NULL, or set to its original value).

If you see any problems with this code, let me know and I'll correct it. It works for my needs, though my needs do not exercise PHP exhaustively.

Go Top