这个失败:
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);
这似乎是不必要的努力。
当前回答
如果你使用的是php7 & 7+,你也可以像这样使用fetch
define('TEAM', ['guy', 'development team']);
echo TEAM[0];
// output from system will be "guy"
其他回答
从PHP 5.6开始,你可以用const声明一个数组常量:
<?php
const DEFAULT_ROLES = array('guy', 'development team');
短语法也可以,正如你所期望的那样:
<?php
const DEFAULT_ROLES = ['guy', 'development team'];
如果你有PHP 7,你最终可以使用define(),就像你第一次尝试的那样:
<?php
define('DEFAULT_ROLES', array('guy', 'development team'));
使用某种ser/deser或encode/decode技巧看起来很难看,并且要求您在尝试使用常量时记住您到底做了什么。我认为class private static variable with accessor是一个不错的解决方案,但我会给你一个更好的。只要有一个返回常量数组定义的公共静态getter方法。这只需要最少的额外代码,并且数组定义不会被意外修改。
class UserRoles {
public static function getDefaultRoles() {
return array('guy', 'development team');
}
}
initMyRoles( UserRoles::getDefaultRoles() );
如果你真的想让它看起来像一个已定义的常量,你可以给它一个全大写的名字,但是记住在名字后面加上'()'括号会让人困惑。
class UserRoles {
public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
}
//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );
我认为您可以将方法设置为全局的,以便更接近您所要求的define()功能,但是无论如何您都应该限定常量名称并避免全局变量。
常量只能包含标量值,我建议您存储数组的序列化(或JSON编码表示)。
PHP 7 +。
从PHP 7开始,你可以使用define()函数定义一个常量数组:
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
如果你使用的是php7 & 7+,你也可以像这样使用fetch
define('TEAM', ['guy', 'development team']);
echo TEAM[0];
// output from system will be "guy"