这个失败:
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);
这似乎是不必要的努力。
当前回答
我知道这是一个有点老的问题,但这是我的解决方案:
<?php
class Constant {
private $data = [];
public function define($constant, $value) {
if (!isset($this->data[$constant])) {
$this->data[$constant] = $value;
} else {
trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
}
}
public function __get($constant) {
if (isset($this->data[$constant])) {
return $this->data[$constant];
} else {
trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
return $constant;
}
}
public function __set($constant,$value) {
$this->define($constant, $value);
}
}
$const = new Constant;
我定义它是因为我需要在常量中存储对象和数组,所以我也安装了runkit到php,这样我就可以使$const变量超全局。
你可以使用它作为$const->define("my_constant",array("my","values"));或者只是$const->my_constant = array("my","values");
要获取该值,只需调用$const->my_constant;
其他回答
PHP 7 +。
从PHP 7开始,你可以使用define()函数定义一个常量数组:
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
从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'));
我知道这是一个有点老的问题,但这是我的解决方案:
<?php
class Constant {
private $data = [];
public function define($constant, $value) {
if (!isset($this->data[$constant])) {
$this->data[$constant] = $value;
} else {
trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
}
}
public function __get($constant) {
if (isset($this->data[$constant])) {
return $this->data[$constant];
} else {
trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
return $constant;
}
}
public function __set($constant,$value) {
$this->define($constant, $value);
}
}
$const = new Constant;
我定义它是因为我需要在常量中存储对象和数组,所以我也安装了runkit到php,这样我就可以使$const变量超全局。
你可以使用它作为$const->define("my_constant",array("my","values"));或者只是$const->my_constant = array("my","values");
要获取该值,只需调用$const->my_constant;
常量只能包含标量值,我建议您存储数组的序列化(或JSON编码表示)。
如果你使用的是php7 & 7+,你也可以像这样使用fetch
define('TEAM', ['guy', 'development team']);
echo TEAM[0];
// output from system will be "guy"