Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php const arrays

Tags:

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;     }  } 
like image 682
Marty Wallace Avatar asked Aug 26 '12 09:08

Marty Wallace


People also ask

Can an array be a const PHP?

Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

Can you use const in PHP?

You can Declare Constants within a PHP Class using the const Keyword. Unlike the define function, you can use the const keyword to declare a constant within a class.

Can const be an array?

The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

What is const function in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).


2 Answers

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(...); 
like image 158
Niko Avatar answered Sep 18 '22 15:09

Niko


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')); 
like image 44
cgaldiolo Avatar answered Sep 17 '22 15:09

cgaldiolo