tags:

views:

95

answers:

4

hello. is there a way to define a constant array in PHP?

+6  A: 

No, it's not possible. From the manual: Constants Syntax

Only scalar data (boolean, integer, float and string) can be contained in constants. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

If you need to set a defined set of constants, consider creating a class and filling it with class constants. A slightly modified example from the manual:

class MyClass
{
const constant1 = 'constant value';
const constant2 = 'constant value';
const constant3 = 'constant value';

  function showConstant1() {
    echo  self::constant1 . "\n";
  }
}

echo MyClass::constant3;

Also check out the link GhostDog posted, it's a nice workaround.

Pekka
+1  A: 

don't think you can. But you can always try searching.

ghostdog74
The downvote is unjustified, the link points to a very good resource.
Pekka
+1  A: 
define('SOMEARRAY', serialize(array(1,2,3)));

$is_in_array = in_array($x, unserialize(SOMEARRAY));

thats the closest to an array constant.

useless
Thanx: did this and worked great define("DEF_ARR", serialize(array("1", "a", "From.ME.to.YOU"))); foreach (unserialize(DEF_ARR) as $k=>$v) { echo "Key: ".$k." VALUE: ".$v."\n"; }
Phill Pafford
+1  A: 

You can not, but you can just define static array in a class and it would serve you just the same, just instead of FOO you'd write Foo::$bar.

StasM