这个失败:
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);
这似乎是不必要的努力。
当前回答
你可以将它们存储为类的静态变量:
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'];
其他回答
如果您使用的是php5.6或以上版本,请使用Andrea Faulds的答案
我是这样用的。我希望,这将帮助其他人。
config。
class app{
private static $options = array(
'app_id' => 'hello',
);
public static function config($key){
return self::$options[$key];
}
}
在文件中,我需要常数。
require('config.php');
print_r(app::config('app_id'));
你可以将它们存储为类的静态变量:
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'];
如果你使用的是php7 & 7+,你也可以像这样使用fetch
define('TEAM', ['guy', 'development team']);
echo TEAM[0];
// output from system will be "guy"
这就是我用的。它类似于soulmerge提供的示例,但是通过这种方式,您可以获得整个数组或数组中的单个值。
class Constants {
private static $array = array(0 => 'apple', 1 => 'orange');
public static function getArray($index = false) {
return $index !== false ? self::$array[$index] : self::$array;
}
}
像这样使用它:
Constants::getArray(); // Full array
// OR
Constants::getArray(1); // Value of 1 which is 'orange'
使用爆炸和内爆函数,我们可以临时想出一个解决方案:
$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] ;
}
希望这能有所帮助。快乐编码。