views:

838

answers:

7

This failed:

 define('DEFAULT_ROLES', array('guy', 'development team'));

Apparently, constants can't hold arrays. What is the best way to get around this?

define('DEFAULT_ROLES', 'guy|development team');

//...

$default = split(DEFAULT_ROLES, '|');

This seems like unnecessary effort.

A: 

Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.

Alix Axel
+1  A: 

Can you not just do:

$DEFAULT_ROLES = array('guy', 'development team');
John Rasch
Anyone care to explain what's wrong with this?
John Rasch
the whole point of constants is to make something that can't be altered.
Rosarch
Of course that's the point of constants, except PHP doesn't support constant arrays, no matter what you do they will be mutable. Why create an entire class for one constant? Why split a string to create the array as opposed to just defining as an array from the start?
John Rasch
I agree with John—PHP should allow array constants. Perl permits that, and array constants in Perl can be quite handy.
nohat
+1  A: 

You can store them as static variables of a class:

class Constants {
    public static $array = array('guy', 'development team');
}
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';

If you don't like the idea that the array can be changed by others, a getter might help:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
    }
}
$constantArray = Constants::getArray();
soulmerge
A: 

I agree with eyze, constants tend to be single value values needed for the entire life of your application. You might think about using a configuration file instead of constants for this sort of thing.

If you really need constant arrays, you could use naming conventions to somewhat mimic arrays: for instance DB_Name, DB_USER, DB_HOST, etc.

Robert DeBoer
A: 

That is correct, you cannot use arrays for a constant, only scaler and null. The idea of using an array for constants seem a bit backwards to me.

What I suggest to do instead is define your own constant class and use that to get the constant.

Daniel
+4  A: 

You can also serialize your array and then put it into the constant:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);

HTH, flokra

flokra
A: 

But you can convert an whole array to constants see link text

Hasan Khan