这个失败:
define('DEFAULT_ROLES', array('guy', 'development team'));
显然,常量不能保存数组。解决这个问题的最好方法是什么?
define('DEFAULT_ROLES', 'guy|development team');
//...
$default = explode('|', DEFAULT_ROLES);
这似乎是不必要的努力。
这个失败:
define('DEFAULT_ROLES', array('guy', 'development team'));
显然,常量不能保存数组。解决这个问题的最好方法是什么?
define('DEFAULT_ROLES', 'guy|development team');
//...
$default = explode('|', DEFAULT_ROLES);
这似乎是不必要的努力。
当前回答
您可以将其作为JSON字符串存储在常量中。从应用程序的角度来看,JSON在其他情况下也很有用。
define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));
$fruits = json_decode (FRUITS);
var_dump($fruits);
其他回答
PHP 5.6+引入了const数组——参见Andrea Faulds的回答。
你也可以序列化你的数组,然后把它放入常量:
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
# use it
$my_fruits = unserialize (FRUITS);
PHP 7 +。
从PHP 7开始,你可以使用define()函数定义一个常量数组:
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
使用爆炸和内爆函数,我们可以临时想出一个解决方案:
$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1];
这将回复邮件。
如果你想让它更优化,你可以定义2个函数来做重复的事情,像这样:
//function to define constant
function custom_define ($const , $array) {
define($const, implode (',' , $array));
}
//function to access constant
function return_by_index ($index,$const = DEFAULT_ROLES) {
$explodedResult = explode(',' ,$const ) [$index];
if (isset ($explodedResult))
return explode(',' ,$const ) [$index] ;
}
希望这能有所帮助。快乐编码。
是的,你可以将数组定义为常量。从PHP 5.6开始,可以将常量定义为标量表达式,也可以定义数组常量。可以将常量定义为资源,但应该避免这样做,因为这会导致意想不到的结果。
<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';
echo CONSTANT;
// Works as of PHP 5.6.0
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;
const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"
// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
?>
参考此链接
有一个快乐的编码。
你可以将它们存储为类的静态变量:
class Constants {
public static $array = array('guy', 'development team');
}
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';
如果你不喜欢数组可以被其他人更改的想法,getter可能会有所帮助:
class Constants {
private static $array = array('guy', 'development team');
public static function getArray() {
return self::$array;
}
}
$constantArray = Constants::getArray();
EDIT
从PHP5.4开始,甚至可以在不需要中间变量的情况下访问数组值,即以下工作:
$x = Constants::getArray()['index'];