PHP Constants: Can They Embrace Arrays?
Attempting to define a constant containing an array in PHP may encounter a snag, as the code provided reveals. Constants are inherently rigid in their data storage, leaving room for the question of how to circumvent this limitation.
One proposed workaround involves storing the array elements in a string separated by a delimiter. While this method serves the purpose, it introduces unnecessary conversion overhead.
However, PHP has evolved since the query was posed. PHP 5.6 and later introduce the possibility of declaring an array constant using the const keyword. This eliminates the need for conversion to and from strings:
const DEFAULT_ROLES = array('guy', 'development team');
The concise syntax also functions as expected:
const DEFAULT_ROLES = ['guy', 'development team'];
If your PHP version is 7 or higher, you can finally utilize the define() function as initially attempted:
define('DEFAULT_ROLES', array('guy', 'development team'));
Thus, the quandary of storing arrays in PHP constants has been resolved with the evolution of the language, offering direct and seamless definition of array constants.
The above is the detailed content of Can PHP Constants Hold Arrays?. For more information, please follow other related articles on the PHP Chinese website!