PHP 常量包含数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1290318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:54:05  来源:igfitidea点击:

PHP Constants Containing Arrays?

phparraysconstantsscalar

提问by Nick Heiner

This failed:

这失败了:

 define('DEFAULT_ROLES', array('guy', 'development team'));

Apparently, constants can't hold arrays. What is the best way to get around this?

显然,常量不能容纳数组。解决这个问题的最佳方法是什么?

define('DEFAULT_ROLES', 'guy|development team');

//...

$default = explode('|', DEFAULT_ROLES);

This seems like unnecessary effort.

这似乎是不必要的努力。

回答by Andrea

Since PHP 5.6, you can declare an array constant with const:

自 PHP 5.6 起,您可以使用以下命令声明数组常量const

<?php
const DEFAULT_ROLES = array('guy', 'development team');

The short syntax works too, as you'd expect:

正如您所期望的那样,简短的语法也有效:

<?php
const DEFAULT_ROLES = ['guy', 'development team'];

If you have PHP 7, you can finally use define(), just as you had first tried:

如果你有 PHP 7,你终于可以使用define(),就像你第一次尝试的那样:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));

回答by Andrea

NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.

注意:虽然这是公认的答案,但值得注意的是,在 PHP 5.6+ 中,您可以拥有 const 数组 -请参阅下面的 Andrea Faulds 的答案

You can also serialize your array and then put it into the constant:

您还可以序列化您的数组,然后将其放入常量中:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);

回答by soulmerge

You can store them as static variables of a class:

您可以将它们存储为类的静态变量:

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';

If you don't like the idea that the array can be changed by others, a getter might help:

如果您不喜欢其他人可以更改数组的想法,则 getter 可能会有所帮助:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
    }
}
$constantArray = Constants::getArray();

EDIT

编辑

Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:

从 PHP5.4 开始,甚至可以在不需要中间变量的情况下访问数组值,即以下工作:

$x = Constants::getArray()['index'];

回答by Jashwant

If you are using PHP 5.6 or above, use Andrea Faulds answer

如果您使用的是 PHP 5.6 或更高版本,请使用 Andrea Faulds 答案

I am using it like this. I hope, it will help others.

我正在这样使用它。我希望,它会帮助别人。

config.php

配置文件

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

In file, where I need constants.

在文件中,我需要常量。

require('config.php');
print_r(app::config('app_id'));

回答by Syclone

This is what I use. It is similar to the example provided by soulmerge, but this way you can get the full array or just a single value in the array.

这就是我使用的。它类似于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;
    }
}

Use it like this:

像这样使用它:

Constants::getArray(); // Full array
// OR 
Constants::getArray(1); // Value of 1 which is 'orange'

回答by Mahesh Talpade

You can store it as a JSON string in a constant. And application point of view, JSON can be useful in other cases.

您可以将其作为 JSON 字符串存储在常量中。从应用程序的角度来看,JSON 在其他情况下也很有用。

define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
$fruits = json_decode (FRUITS);    
var_dump($fruits);

回答by Altaf Hussain

Starting with PHP 5.6, you can define constant arrays using constkeyword like below

从 PHP 5.6 开始,您可以使用const如下关键字定义常量数组

const DEFAULT_ROLES = ['test', 'development', 'team'];

and different elements can be accessed as below:

可以访问不同的元素,如下所示:

echo DEFAULT_ROLES[1]; 
....

Starting with PHP 7, constant arrays can be defined using defineas below:

从 PHP 7 开始,可以使用define如下定义常量数组:

define('DEFAULT_ROLES', [
    'test',
    'development',
    'team'
]);

and different elements can be accessed same way as before.

并且可以像以前一样访问不同的元素。

回答by Thielicious

Can even work with Associative Arrays.. for example in a class.

甚至可以使用关联数组……例如在类中。

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.

回答by Rikudou_Sennin

I know it's a bit old question, but here is my solution:

我知道这是一个有点老的问题,但这是我的解决方案:

<?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;

I defined it because I needed to store objects and arrays in constants so I installed also runkit to php so I could make the $const variable superglobal.

我定义它是因为我需要将对象和数组存储在常量中,所以我还安装了 runkit 到 php,这样我就可以使 $const 变量成为超全局变量。

You can use it as $const->define("my_constant",array("my","values"));or just $const->my_constant = array("my","values");

您可以将其用作$const->define("my_constant",array("my","values"));或仅使用$const->my_constant = array("my","values");

To get the value just simply call $const->my_constant;

要获得价值只需简单地调用 $const->my_constant;

回答by Daniel Skarbek

Doing some sort of ser/deser or encode/decode trick seems ugly and requires you to remember what exactly you did when you are trying to use the constant. I think the class private static variable with accessor is a decent solution, but I'll do you one better. Just have a public static getter method that returns the definition of the constant array. This requires a minimum of extra code and the array definition cannot be accidentally modified.

执行某种 ser/deser 或编码/解码技巧似乎很丑陋,并且需要您记住在尝试使用常量时究竟做了什么。我认为带有访问器的类私有静态变量是一个不错的解决方案,但我会为您做一个更好的。只需有一个返回常量数组定义的公共静态 getter 方法。这需要最少的额外代码,并且不会意外修改数组定义。

class UserRoles {
    public static function getDefaultRoles() {
        return array('guy', 'development team');
    }
}

initMyRoles( UserRoles::getDefaultRoles() );

If you want to really make it look like a defined constant you could give it an all caps name, but then it would be confusing to remember to add the '()' parentheses after the name.

如果你真的想让它看起来像一个定义的常量,你可以给它一个全大写的名字,但是记住在名字后面添加“()”括号会让人困惑。

class UserRoles {
    public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
}

//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );

I suppose you could make the method global to be closer to the define() functionality you were asking for, but you really should scope the constant name anyhow and avoid globals.

我想您可以使方法全局更接近您要求的define() 功能,但无论如何您确实应该确定常量名称的范围并避免使用全局变量。