PHP const数组
这是在php中将数组作为常量的唯一方法,还是这样的错误代码:
class MyClass
{
private static $myArray = array('test1','test2','test3');
public static function getMyArray()
{
return self::$myArray;
}
}
Marty Wallace asked 2019-11-10T16:01:11Z
7个解决方案
73 votes
您的代码很好-数组不能在5.6版之前的PHP中声明为常量,因此静态方法可能是最好的方法。 您应该考虑通过注释将此变量标记为常量:
/** @const */
private static $myArray = array(...);
使用PHP 5.6.0或更高版本,您可以声明数组常量:
const myArray = array(...);
Niko answered 2019-11-10T16:01:42Z
18 votes
从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(2015年12月3日)时,可以使用define()定义数组常量。 在PHP 5.6中,只能使用const定义它们。 (请参阅PHP 7.0.0的新功能)
define('MYARRAY', array('test1','test2','test3'));
cgaldiolo answered 2019-11-10T16:02:14Z
9 votes
我碰到了这个话题,自己寻找答案。 经过思考,我必须将数组传递给需要的所有函数。我对数组和mysql的经验使我怀疑序列化是否可以工作。 当然可以。
define("MYARRAY", serialize($myarray));
function something() {
$myarray= unserialize(MYARRAY);
}
pokeybit answered 2019-11-10T16:02:41Z
1 votes
将其标记为静态是一个不错的选择。 这是封装静态数组以获得某种恒定行为的示例。
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') );
打印:
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) }
Joe answered 2019-11-10T16:03:08Z
1 votes
我建议使用以下内容:
class MyClass
{
public static function getMyArray()
{
return array('test1','test2','test3');
}
}
这样,您就可以拥有一个const数组,并且可以确保没有人可以更改它,即使Class本身也不可以更改它。
可能的微优化(不确定当今有多少PHP编译器优化):
class MyClass
{
public static function getMyArray()
{
static $myArray = array('test1','test2','test3');
return $myArray;
}
}
Kirab answered 2019-11-10T16:03:46Z
1 votes
您创建了一个静态数组,而不是一个常量数组。 静态变量是可变的; 常量是不可变的。 您的代码还不错,但是它并没有达到您的预期目的。
在PHP 5.6中,可以声明$数组。 请参阅我之前的解释。
也许您想要这样的东西:
class MyClass
{
const MY_ARRAY = array('test1','test2','test3');
public function getMyArray()
{
return MY_ARRAY;
}
}
请注意,常量没有前缀$,表示它们的不变性。 $foo是变量; FOO不是。 此外,常量名总是大写的,至少在我接触过的编程语言中是如此。 这不是由编译器强制执行的。 它只是(几乎?)通用编码样式约定。 可见性关键字public、protected和private不适用于常量。 最后,取决于您是否希望函数为static,static可能适用也可能适用。
jfmercer answered 2019-11-10T16:04:39Z
0 votes
从PHP 5.6起,可以将常量定义为标量表达式,也可以定义数组常量。
class foo {
const KEYS = [1, 3, 6, 7];
}
//
echo foo::KEYS[0]; // 1
Rabih answered 2019-11-10T16:05:07Z