php const arrays

php
2022-08-30 09:11:18

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

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

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

答案 1

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

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

使用 PHP 5.6.0 或更高版本,您可以将数组声明为常量:

const myArray = array(...);

答案 2

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

使用 PHP 7.0.0 (03 Dec 2015),数组常量可以使用 define() 定义。在 PHP 5.6 中,它们只能使用 const. 进行定义(参见 PHP 7.0.0 新功能。)

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

推荐