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
2010-02-11 01:16:14
The downvote is unjustified, the link points to a very good resource.
Pekka
2010-02-11 01:25:21
+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
2010-02-11 01:51:53
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
2010-05-27 16:57:20
+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
2010-02-11 02:20:00