失败了:
define('DEFAULT_ROLES', array('guy', 'development team'));
显然,常量不能保存数组。解决这个问题的最佳方法是什么?
define('DEFAULT_ROLES', 'guy|development team');
//...
$default = explode('|', DEFAULT_ROLES);
这似乎是不必要的努力。
从 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 5.6+ 引入了
数组 - 参见 Andrea Faulds 的回答。const
您还可以序列化数组,然后将其放入常量中:
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
# use it
$my_fruits = unserialize (FRUITS);
您可以将它们存储为类的静态变量:
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();
编辑
从 PHP5.4 开始,甚至可以访问数组值而不需要中间变量,即以下工作:
$x = Constants::getArray()['index'];
我就是这样使用的。我希望,它会帮助其他人。
config.php
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'));
我用的就是这个。它与 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'
您可以将其作为 JSON 字符串存储在常量中。从应用程序的角度来看,JSON 在其他情况下也很有用。
define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));
$fruits = json_decode (FRUITS);
var_dump($fruits);
从 PHP 7 开始,您可以使用 define() 函数来定义常量数组:
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
我知道这是一个有点老的问题,但这是我的解决方案:
<?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 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 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.
如果您使用 PHP 7 和 7+,您也可以像这样使用 fetch
define('TEAM', ['guy', 'development team']);
echo TEAM[0];
// output from system will be "guy"
使用爆炸和内爆函数,我们可以即兴解决方案:
$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1];
这将回响
email
。
如果你想让它进一步优化,你可以定义 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] ;
}
希望有帮助。快乐编码。
执行某种 Ser/deser 或编码/解码技巧看起来很丑陋,并且要求您记住当您尝试使用常量时到底做了什么。我认为带有访问器的类私有静态变量是一个不错的解决方案,但我会给你一个更好的解决方案。只需有一个公共静态 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() 功能,但无论如何你真的应该限制常量名称的范围并避免全局。
你可以这样定义
define('GENERIC_DOMAIN',json_encode(array(
'gmail.com','gmail.co.in','yahoo.com'
)));
$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);
常量只能包含标量值,我建议您存储数组的序列化(或 JSON 编码表示)。
如果您从 2009 年开始查看此内容,并且不喜欢 AbstractSingletonFactoryGenerators,这里还有一些其他选项。
请记住,数组在分配时会被“复制”,或者在本例中返回时会被“复制”,因此实际上每次都会获得相同的数组。 (请参阅 PHP 中数组的写时复制行为。)
function FRUITS_ARRAY(){
return array('chicken', 'mushroom', 'dirt');
}
function FRUITS_ARRAY(){
static $array = array('chicken', 'mushroom', 'dirt');
return $array;
}
function WHAT_ANIMAL( $key ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $array[ $key ];
}
function ANIMAL( $key = null ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $key !== null ? $array[ $key ] : $array;
}
警告如果您使用 spl_autoload_register(..) 函数并使用数组定义常量,则类注册顺序按字母顺序排列。我没有得到包含数组的常量,因为我在 B 类中声明了它,并想在 A 类中使用它,我认为常量是全局的,无论它们在哪里声明,但这是错误的!初始化常量的文件的顺序很重要。 希望对您有所帮助。