包含数组的 PHP 常量?

2022-01-23 00:00:00 arrays scalar constants 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);

相关文章