Home >Backend Development >PHP Tutorial >How Can I Define PHP Constants Containing Arrays?
When attempting to define a constant that contains an array using the define() function, you may encounter an error. This is because, prior to PHP 5.6, PHP constants could not contain arrays.
To work around this limitation, a common approach was to store the array as a string in the constant and then explode it into an array when needed. While this method is functional, it does require additional effort and introduces unnecessary string manipulation.
Since PHP 5.6, a new approach is available through the const declaration. To define an array constant using const:
const DEFAULT_ROLES = array('guy', 'development team');
This method is preferred as it allows you to define array constants directly without the need for string manipulation or explode().
In PHP 7 and later, the define() function can also be used to define array constants:
define('DEFAULT_ROLES', array('guy', 'development team'));
Here's an example demonstrating the usage of an array constant defined using const:
const DEFAULT_ROLES = array('guy', 'development team'); $default = DEFAULT_ROLES; // Assign the array constant to a variable
The above is the detailed content of How Can I Define PHP Constants Containing Arrays?. For more information, please follow other related articles on the PHP Chinese website!