这是在php中将数组作为常量的唯一方法,还是这是一个糟糕的代码:
class MyClass
{
private static $myArray = array('test1','test2','test3');
public static function getMyArray()
{
return self::$myArray;
}
}发布于 2012-08-26 18:08:34
您的代码很好-在5.6版本之前的PHP中,数组不能被声明为常量,因此静态方法可能是最好的方法。您应该考虑通过注释将此变量标记为常量:
/** @const */
private static $myArray = array(...);使用PHP 5.6.0或更高版本,您可以声明数组常量:
const myArray = array(...);发布于 2015-05-04 21:53:25
从PHP5.6.0(2014年8月28日)开始,可以定义数组常量(参见PHP 5.6.0 new features)。
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()定义。在PHP5.6中,它们只能用const来定义。(参见PHP 7.0.0 new features)
define('MYARRAY', array('test1','test2','test3'));发布于 2013-10-24 15:38:24
我自己在寻找答案的时候遇到了这个帖子。在思考之后,我将不得不将我的数组传递给每个需要它的函数。我使用数组和mysql的经验让我怀疑serialize是否可以工作。当然是这样的。
define("MYARRAY", serialize($myarray));
function something() {
$myarray= unserialize(MYARRAY);
}https://stackoverflow.com/questions/12129066
复制相似问题