php const arrays

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;
    } 
}

Solution 1:

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(...);

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

const myArray = array(...);

Solution 2:

Starting with PHP 5.6.0 (28 Aug 2014), it is possible to define an array constant (See 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'

With PHP 7.0.0 (03 Dec 2015) array constants can be defined with define(). In PHP 5.6, they could only be defined with const. (See PHP 7.0.0 new features)

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

Solution 3:

I came across this thread looking for the answer myself. After thinking I would have to pass my array through every function it was needed in. My experience with arrays and mysql made me wonder if serialize would work. Of course it does.

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

function something() {
    $myarray= unserialize(MYARRAY);
}

Solution 4:

I suggest using the following:

class MyClass
{
    public static function getMyArray()
    {
       return array('test1','test2','test3');
    } 
}

This way you do have a const array and you're guaranteed that noone can change it, not even a method in the Class itself.

Possible micro-optimization (not sure how much PHP compilers optimize nowadays):

class MyClass
{
    public static function getMyArray()
    {
       static $myArray = array('test1','test2','test3');
       return $myArray;
    } 
}

Solution 5:

Marking it static is a good alternative. Here's an example of encapsulating a static array to get somewhat of constant behavior.

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') );

Prints:

array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) }