这个失败:
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编码表示)。
其他回答
你可以这样定义
define('GENERIC_DOMAIN',json_encode(array(
'gmail.com','gmail.co.in','yahoo.com'
)));
$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);
甚至可以与关联数组工作..例如在课堂上。
class Test {
const
CAN = [
"can bark", "can meow", "can fly"
],
ANIMALS = [
self::CAN[0] => "dog",
self::CAN[1] => "cat",
self::CAN[2] => "bird"
];
static function noParameter() {
return self::ANIMALS[self::CAN[0]];
}
static function withParameter($which, $animal) {
return "who {$which}? a {$animal}.";
}
}
echo Test::noParameter() . "s " . Test::CAN[0] . ".<br>";
echo Test::withParameter(
array_keys(Test::ANIMALS)[2], Test::ANIMALS["can fly"]
);
// dogs can bark.
// who can fly? a bird.
如果您使用的是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'));
使用爆炸和内爆函数,我们可以临时想出一个解决方案:
$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
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;