Viewed   111 times

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 = explode('|', DEFAULT_ROLES);

This seems like unnecessary effort.



NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.

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);
Wednesday, November 23, 2022


This is now available in PHP 5.6

No you can't assign an Array to PHP constant.


Constants may only evaluate to scalar values

This is the reason.

Scalar values for examples are int, float, string

Thursday, December 22, 2022

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*

From: Constants (PHP mamual)

Thursday, November 3, 2022

I think this is in the realm of being a micro-optimization. That is, the difference is small enough that it isn't worth using one solution over the other for the sake of performance. If performance were that critical to your app, you wouldn't be using PHP! :-)

Use whatever is more convenient or that makes more sense. I put config data into constants if only because they shouldn't be allowed to change after the config file is loaded, and that's what constants are for.

Tuesday, August 23, 2022

Define statements are in general only commented with a descriptive text, so that's basically how you comment it.

To read more about the DocBlock template tag, /**#@+, check out the manual page.

Monday, August 22, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :