PHP const数组 [英] php const arrays

查看:97
本文介绍了PHP const数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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:

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

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

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

const myArray = array(...);

这篇关于PHP const数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆