PHP Constants Containing Arrays?(包含数组的 PHP 常量?)
问题描述
这失败了:
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.
推荐答案
注意:虽然这是公认的答案,但值得注意的是,在 PHP 5.6+ 中,您可以使用 const 数组 - 请参阅下面 Andrea Faulds 的回答.
你也可以序列化你的数组,然后放入常量中:
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);
这篇关于包含数组的 PHP 常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!