I have a small PHP script where it makes sense to use globals. One of the globals is an array that simply contains values to be unpacked but not modified by several different functions. If the script ever expands, the idea of having a global array is a bit unsettling. Is there any way to turn a global array into a constant, unmodifiable value? And if so, will I still be allowed to use the implode()
function on it?

- 11,158
- 28
- 90
- 132
-
Have you googled "PHP constants" and found this http://php.net/manual/en/language.constants.php ? – Popnoodles Mar 07 '13 at 18:31
-
3Using ENUMS in PHP http://stackoverflow.com/questions/254514/php-and-enums – Mike B Mar 07 '13 at 18:33
-
@popnoodles Indeed I have. Was wondering if there was a workaround. – user1427661 Mar 07 '13 at 18:33
-
The long-winded workaround is constructing an `ArrayObject` with `offsetSet` disabled for a readonly array. – mario Mar 07 '13 at 18:48
4 Answers
PHP constants do not support advanced data structures, so it is not possible to store an array as the value of a constant. Unless you were to do as you mentioned, by exploding the string.
There are several global variables (called superglobals) which are available from all PHP scope:
- $_GET
- $_POST
- $_REQUEST
- $_SERVER
- $GLOBALS
I'd highly suggest making use of $GLOBALS
, and place your array within that array. It'll immediately be available in any function, class, or included file.
<?php
$GLOBALS['my_arr'] = array('key1' => 'val1', 'key2' => 'val2');
function my_func() {
return $GLOBALS['my_arr']['key1'];
}
print my_func(); // prints: val1
While you could serialize a constant's value or explode it whenever you wanted to grab a value from it, keep in mind transformation operations do take time. Serializing an array, un-serializing a string, or exploding a string are all very unnecessary operations when you can simply append a value to $GLOBALS
. If you need to reference a single value from three different scopes in your script, you're forced to un-serialize or explode three separate times. This takes up more memory and most importantly, processing time.

- 8,268
- 4
- 48
- 61
I'm scared to definitively say "no, you can't" but I'm pretty sure that's the case. What you can do is create a static function somewhere that will always return the same array of values. Would that solve your problem?

- 4,280
- 2
- 19
- 17
You could serialize the array and define a constant in your script;
define("GLOBAL_DATA", "xxxxxxxx"); -- use the serialized array
Any function can now unserialize the constant and get the original array, knowing that it hasn't been modified.

- 799
- 4
- 10
Convert it to JSON using PHP's json_encode() function, and use json_decode() to convert it back to a string.
Example:
<?php
define('CONSTANT',json_encode(array('test')));
//Use the constant:
if(in_array('CONSTANT',json_decode(constant('CONSTANT')))) {
return true;
} else {
return false;
}
?>

- 1
- 4