php const数组

Mar*_*ace 57 php

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

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

    public static function getMyArray()
    {
       return self::$myArray;
    } 
}
Run Code Online (Sandbox Code Playgroud)

Nik*_*iko 74

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

/** @const */
private static $myArray = array(...);
Run Code Online (Sandbox Code Playgroud)

使用PHP 5.6.0或更高版本,您可以声明数组不变:

const myArray = array(...);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,变量$ myArray本身可以更改,从这个意义上说它不如常量安全.如果你不能使用私有或保护,那么我认为没有解决方案安全的PHP阵列. (6认同)

cga*_*olo 18

从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'
Run Code Online (Sandbox Code Playgroud)

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

define('MYARRAY', array('test1','test2','test3'));
Run Code Online (Sandbox Code Playgroud)


pok*_*bit 9

我遇到了这个线程,自己寻找答案.在想到我必须通过我需要的每个函数传递我的数组.我对数组和mysql的经验让我想知道序列化是否会起作用.当然可以.

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

function something() {
    $myarray= unserialize(MYARRAY);
}
Run Code Online (Sandbox Code Playgroud)