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.
Can even work with Associative Arrays.. for example in a class.
Using explode and implode function we can improvise a solution :
This will echo
email
.If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :
Hope that helps . Happy coding .
You might also explode the array into a series of constants. (a pretty old school solution) After all, the array is constant, so the only reason you need it for, is global, fast, lookup of certain keys.
Hence this:
Would turn into:
Yes, there's namespace pollution (and a lot of prefixing to prevent it) to take into account.
PHP 7+
As of PHP 7, you can just use the define() function to define a constant array :
Since PHP 5.6, you can declare an array constant with
const
:The short syntax works too, as you'd expect:
If you have PHP 7, you can finally use
define()
, just as you had first tried:Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.
With the reference of this link
Have a happy coding.