73

Possible Duplicate:
Is it possible to declare an array as constant

Is it possible to use an array as a class constant in PHP?

I.e

const MYARRAY = array('123', '234');

If not why?

4
  • 1
    please use the search function before asking questions. we expect you to do research. Commented Jun 25, 2012 at 7:15
  • 15
    The duplicate discussed constants created using define(). Rules for class constants are not the same. Voting to reopen. Commented Apr 10, 2013 at 6:56
  • You can somewhat convert an array to a string and store it as a constant. When you need it, you just reconvert it. Look into the (un)serialize example: stackoverflow.com/questions/1290318/… Commented Jun 27, 2013 at 7:58
  • 1
    @Jack, I agree because I find a way to do what I need (xdazz answer) thanks to this question - we aren't only interested in answer like "No, it isn't posibble", but in that which tells us how to do what we want. Commented Apr 25, 2014 at 12:41

2 Answers 2

77

No, you can't.

But you could declare it as a static property.

public static $MYARRAY = array('123', '234');

---------------Update-----------------------------

Array const is available from PHP 5.6.

php.net/manual/en/migration56.new-features.php

Sign up to request clarification or add additional context in comments.

5 Comments

This wouldn't be the same as a constant though as the value could be changed
@Martin Yep, that's true, but you can not declare a constant with an array.
Can a static be declared private at least?
@Martin Furthermore, you can declare a public getter if you wanted something like a public constant.
Then I got this Strict Standards: Accessing static property
70

UPDATE:

This is now available in PHP 5.6 https://php.net/manual/en/migration56.new-features.php


No you can't assign an Array to PHP constant.

In http://www.php.net/manual/en/language.constants.syntax.php

Constants may only evaluate to scalar values

This is the reason.

Scalar values for examples are int, float, string

1 Comment

This is now available in PHP 5.6 php.net/manual/en/migration56.new-features.php

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.