Constant containing Array (matrix)

Asked

Viewed 90 times

2

When I try to define a constant as an Array gives error.

define('COLORS', ['red', 'blue', 'green']);

Is there any way to define an Array in the value of a constant?

3 answers

3

The manual answers:

Until PHP 5.6, only scalar data (Boolean, integer, float, and string) can be put into constants. Starting with PHP 5.6, you can also use an array as a constant value. The use of a Resource (resource) as a constant value is allowed, but should be avoided as it may cause unexpected results.

  • Can I adapt an answer in the gringo OS here? It is possible to set an "array" before PHP 5.6, but only with the use of a function.

  • Go ahead. If you want to edit my answer, I’ll make it "community wiki". If you prefer, you can post a separate reply.

  • I’m new to the O.R. I don’t know what a community wiki is... I already answered my question.

  • 1

    Your answer was very good! To clarify, Wiki Community is a mark that we can make in the reply to indicate that it is collaborative. It becomes collective authorship, and no one gets points for the votes she gets.

3


Before PHP 5.6:
It is possible to do a gambiarra using the functions serialize() and unserialize():

define('COLORS', serialize(['red', 'blue', 'green']));
unserialize(COLORS);


From PHP 5.6:
Like bfavaretto mentioned, the PHP documentation tells us this:

Until PHP 5.6, only scalar data (Boolean, integer, float, and string) can be put into constants. Starting with PHP 5.6, you can also use an array as a constant value. The use of a Resource (resource) as a constant value is allowed, but should be avoided as it may cause unexpected results.

It is possible to define a constant directly containing an array in this way:

const COLORS = ['red', 'blue', 'green'];

NOTE: I did some tests and realized that the values in the Array defined in constants must also be of the type climb or another Array. Ex.:
This is NOT allowed: const CLASSES = ['anyClass' => new anyClass()];


Only from PHP 7.0 which is expected to come out in November 2015, it will be possible to define an Array directly in the function define() thus:

define('COLORS', ['red', 'blue', 'green']);

-1

$colors = array("red","blue","green") will be just fine.
  • 3

    I want a constant... not a variable...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.