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?
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.
Comments
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;
}
?>
ArrayObjectwithoffsetSetdisabled for a readonly array.