Reputation: 43491
define('VAR_1', 'Some info 01');
define('VAR_2', 'Some info 02');
define('VAR_3', 'Some info 03');
define('VAR_4', 'Some info 04');
define('VAR_5', 'Some info 05');
define('VAR_6', 'Some info 06');
define('VAR_7', 'Some info 07');
Upvotes: 2
Views: 1441
Reputation: 25781
I usually namespace my constants, if I've got many of them, in a class like so:
class Foo {
const Bar = 1;
const Baz = 2;
public static $array = array(1,2,3);
}
echo Foo::Bar; # Accessing the constants
print_r(Foo:$array);
Putting an Array in a constant is not possible for class constants, and I don't think it is a good practice putting them in global constants either, if it is even possible (not sure). Maybe you should tell us what you are trying to accomplish, maybe there is a better way to do it.
Oh, and please don't do something like this:
for($x=0; x<10; $x++) {
define('VAR_' . $x, 'Information #' . $x);
}
Which has been suggested here, but IMHO this is absolutely not how constant are supposed to be used.
Upvotes: 4
Reputation: 57268
as already stated it is advised that you encapsulate your constants so that it does not overflow your root scope, try create a class and set your constants in that, such as:
final abstract class Constants
{
const FOO = 'a';
const BAR = 1;
const ZED = 'c';
}
And then simply use like use like so:
echo Constants::FOO;
You should not really be using constants for storing arrays, which is why it has not been allowed within the PHP core.
but im not here to question your motives so if you want to store arrays within a constants then you can do so by transforming into a string, such as
define('MY_ARRAY',serialize(array(1 => 'foo')));
and then run unserialize to get it back into an array
Upvotes: 0
Reputation: 10508
Do you mean you want a single constant with multiple values stored internally?
You can set an array as a constant:
define('VAR', array('Some info 01','Some info 02',...));
In this way, VAR[0] == 'Some info 01'
, VAR[1] == 'Some info 02'
, etc.
Is this what you wanted?
You can't define constants with arrays. Thanks to @wiseguy for reminding me.
Upvotes: 0