php php常量数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12129066/
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 02:53:32  来源:igfitidea点击:

php const arrays

php

提问by Marty Wallace

Is this the only way to have arrays as constants in php or is this bad code:

这是在 php 中将数组作为常量的唯一方法还是这个糟糕的代码:

class MyClass
{
    private static $myArray = array('test1','test2','test3');

    public static function getMyArray()
    {
       return self::$myArray;
    } 
}

回答by Niko

Your code is fine - arrays cannot be declared constant in PHP before version 5.6, so the static approach is probably the best way to go. You should consider marking this variable as constant via a comment:

您的代码很好 - 在 PHP 5.6 之前的版本中不能将数组声明为常量,因此静态方法可能是最好的方法。您应该考虑通过注释将此变量标记为常量:

/** @const */
private static $myArray = array(...);

With PHP 5.6.0 or newer, you can declare arrays constant:

在 PHP 5.6.0 或更新版本中,您可以声明数组常量:

const myArray = array(...);

回答by cgaldiolo

Starting with PHP 5.6.0 (28 Aug 2014), it is possible to define an array constant (See PHP 5.6.0 new features).

从 PHP 5.6.0(2014 年 8 月 28 日)开始,可以定义数组常量(请参阅PHP 5.6.0 新功能)。

class MyClass
{
    const MYARRAY = array('test1','test2','test3');

    public static function getMyArray()
    {
        /* use `self` to access class constants from inside the class definition. */
        return self::MYARRAY;
    } 
}

/* use the class name to access class constants from outside the class definition. */
echo MyClass::MYARRAY[0]; // echo 'test1'
echo MyClass::getMyArray()[1]; // echo 'test2'

$my = new MyClass();
echo $my->getMyArray()[2]; // echo 'test3'

With PHP 7.0.0 (03 Dec 2015) array constants can be defined with define(). In PHP 5.6, they could only be defined with const. (See PHP 7.0.0 new features)

在 PHP 7.0.0(2015 年 12 月 3 日)中,可以使用 define() 定义数组常量。在 PHP 5.6 中,它们只能用 const 定义。(见PHP 7.0.0 新特性

define('MYARRAY', array('test1','test2','test3'));

回答by pokeybit

I came across this thread looking for the answer myself. After thinking I would have to pass my array through every function it was needed in. My experience with arrays and mysql made me wonder if serialize would work. Of course it does.

我遇到了这个线程寻找自己的答案。在考虑我必须通过它需要的每个函数传递我的数组之后。我在数组和 mysql 方面的经验让我想知道序列化是否可行。当然可以。

define("MYARRAY",     serialize($myarray));

function something() {
    $myarray= unserialize(MYARRAY);
}

回答by Joe

Marking it static is a good alternative. Here's an example of encapsulating a static array to get somewhat of constantbehavior.

将其标记为静态是一个不错的选择。这是封装静态数组以获得某种恒定行为的示例。

class ArrayConstantExample {

    private static $consts = array(
        'CONST_MY_ARRAY' => array(
            1,2,3,4
        )
    );

    public static function constant($name) {
        return self::$consts[$name];
    }

}

var_dump( ArrayConstantExample::constant('CONST_MY_ARRAY') );

Prints:

印刷:

array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) }

回答by Kira M. Backes

I suggest using the following:

我建议使用以下内容:

class MyClass
{
    public static function getMyArray()
    {
       return array('test1','test2','test3');
    } 
}

This way you do have a const array and you're guaranteed that noone can change it, not even a method in the Class itself.

这样你就有了一个 const 数组,并且你可以保证没有人可以改变它,甚至不能改变类本身的方法。

Possible micro-optimization (not sure how much PHP compilers optimize nowadays):

可能的微优化(不确定现在 PHP 编译器优化了多少):

class MyClass
{
    public static function getMyArray()
    {
       static $myArray = array('test1','test2','test3');
       return $myArray;
    } 
}

回答by jfmercer

You have created a static array, nota constant array. Static variables are mutable; constants are immutable. Your code is not bad, but it doesn't do what you intend it to do.

您创建了一个静态数组,而不是一个常量数组。静态变量是可变的;常量是不可变的。你的代码还不错,但它没有按照你的意图去做。

In PHP 5.6, you can declare constarrays. Please see my previous explanation.

在 PHP 5.6 中,您可以声明const数组。请看我之前的解释

Perhaps you want something like this:

也许你想要这样的东西:

class MyClass
{
    const MY_ARRAY = array('test1','test2','test3');

    public function getMyArray()
    {
       return MY_ARRAY;
    } 
}

Note that constants have no $prefix, which indicates their immutability. $foois a variable; FOOis not. Additionally, constant names are always capitalized, at least in the programming languages I've been exposed to. This is not enforced by the compiler; it is simply an (almost?) universal coding style convention. Visibility keywords public, protected, and privatedo not apply to constants. Finally, staticmay or may apply depending on whether or not you want the function to be static.

请注意,常量没有$前缀,这表明它们的不变性。$foo是一个变量;FOO不是。此外,常量名称总是大写,至少在我接触过的编程语言中是这样。这不是由编译器强制执行的;它只是一个(几乎?)通用编码风格约定。可见性关键字publicprotectedprivate不适用于常量。最后,static根据您是否希望该功能成为static.

回答by Rabih

From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant.

从 PHP 5.6 开始,可以将常量定义为标量表达式,也可以定义数组常量。

class foo {
   const KEYS = [1, 3, 6, 7];
}
//
echo foo::KEYS[0]; // 1