-1

I know that since php 5.6 you can set a constant as an array, but is it possible to build one dynamically?

This works:

const FIELDS = array("email","firstName");

But I'd like to run a query that populates the constant instead:

while($row = mysqli_fetch_assoc($results)) {
   const FIELDS[] = $row['field'];
}

But that doesn't work. I also tried:

while($row = mysqli_fetch_assoc($results)) {
  $array[] = $row['field'];
}
const FIELDS = $array;

But this also doesn't work. Is there a way to accomplish this? Or does the array have to be hardcoded to be set as a constant?

Matt
  • 175
  • 1
  • 10
  • What about using `define("FIELDS", $array)`? That would require PHP7 though. But a constant is just that - a constant! Why can't you use a variable instead? Is it for usage in a class? – Qirel Aug 25 '17 at 23:04
  • constants are constant. if it changes it is a variable. – Alex Blex Aug 25 '17 at 23:05
  • @AlexBlex I get that, and I'm not trying to make it variable during use, just have the values pulled from a remote source at the time of creation – Matt Aug 25 '17 at 23:07
  • you can use DEFINE('FIELDS', $array) after you have defined $array... but I seriously doubt you really want to do this as defines have no scope and will probably slow your application down. – Phillip Weber Aug 25 '17 at 23:08
  • 1
    You can try to extend ArrayAccess class to implement some sort of immutable array. Of course what you need is not exactly an immutable data structure, but you want to be able to freeze the data structure after initialization. – Nima Aug 25 '17 at 23:13
  • I still think it a major misuse of a constant. `const FIELDS[] = $row['field'];` in the loop changes it on each iteration, not only "at time of creation". The "creation code" is no different from any other part of your script, and if you could change a "constant" in one place, it could be changed anywhere, which would defeat its purpose. – Alex Blex Aug 25 '17 at 23:21

2 Answers2

0

Try using define('FIELDS', $array);. This allows you to use a variable instead of a literal string. Heres some more info about define vs const: define() vs const

The fundamental difference between those two ways is that const defines constants at compile time, whereas define defines them at run time.

Hollings
  • 534
  • 5
  • 14
0

I fully acknowledge this is an improper use of a constant, and I've since changed it to simply use a variable, HOWEVER -- this is how I did find you could accomplish it:

while($row = mysqli_fetch_assoc($results)) {
  $array[] = $row['field'];
}
DEFINE('FIELDS', serialize($array));
print_r(unserialize(FIELDS));

Without first serializing the array, I wasn't able to get the DEFINE approach to work (maybe it's different in 7.0?) This requires you to unserialize it before output.

Matt
  • 175
  • 1
  • 10