PHP doesn’t allow constants to be arrays

If you ever wanted to have a constant containing an array in PHP, you’ll soon notice that the following does not work:

define('MY_CONSTANT', array('value1', 'value2'));

The reason as explained in the PHP language reference is that:

Only scalar data (boolean, integer, float and string) can be contained in constants.

There are three options to come close to a constant containing an array:

  1. Using serialization
  2. Declaring a static property
  3. Using a getter

Using serialization

Since constants can contain a string, the obvious solution is to transform this array to a string.

Either using the serialize function when defining the constant and the unserialize function before using it:

// Define the constant as a serialized array

define('MY_CONSTANT', serialize(array('value1', 'value2')));

// And unserialize it before usage

$my_constant = unserialize(MY_CONSTANT);

or encoding the array to a string yourself, using a separator and using the explode function to convert it back to an array:

// Define the constant as a serialized array

define('MY_CONSTANT', 'value1,value2');

// And unserialize it before usage

$my_constant = explode(',', MY_CONSTANT);

Declaring a static property

As an alternative to a class constant containing an array, you could defined a static property containing the array:

private static $MY_VALUES = array('value1', 'value2');

Of course, it’s not really the same as a constant since the value could be changed so it is less secure than a constant and you should consider making it private or protected.

Using a getter

In order to prevent the static property from being changed, you should make it private and use a public getter e.g.:

private static $MY_VALUES = array('value1', 'value2');

public static function values($index){
    return self::$MY_VALUES[$index];
}

Of course with an associative array, it makes more sense.

You can also use a getter together with the serialization solution so that you do not need to unserialize explicitely every time the array is used:

private const $MY_VALUES = serialize(array('value1', 'value2'));

public static function values(){
    return unserialize(self::$MY_VALUES);
}

Leave a Reply

Your email address will not be published. Required fields are marked *