Marty Wallace Marty Wallace - 4 months ago 17
PHP Question

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

Answer

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