0

I define a constant with:

const NAMES = [
    'boys' => 'john',
    'girls' => 'sue',
];

I try and then call the constant later with:

NAMES['boys']

But get the error:

"Use of undefined constant NAMES - assumed 'NAMES'"

Why is this happening?

EDIT:

It's on a class with PHP7

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
panthro
  • 22,779
  • 66
  • 183
  • 324
  • 1
    @Carcigenicate Constant !== Variable – Mark Baker Nov 03 '17 at 15:08
  • 1
    what php version do you use? if its < 5.6 then constants can't contain arrays. [related question](https://stackoverflow.com/questions/1290318/php-constants-containing-arrays) – kscherrer Nov 03 '17 at 15:09
  • 2
    @panthro Is this defined inside a class? Or just as a constant in the global namespace? – Mark Baker Nov 03 '17 at 15:09
  • 3
    [works for me](http://sandbox.onlinephpfunctions.com/code/bdba2c405a1f74260b9b3ccd3ee9908c78124d38) – apokryfos Nov 03 '17 at 15:09
  • In fact it only fails on hhvm-3.18.5 according to https://3v4l.org/TUa3f – apokryfos Nov 03 '17 at 15:11
  • It's on a class with PHP7 – panthro Nov 03 '17 at 15:11
  • Arrays as constants were added in 5.6, but this would raise a different error on earlier versions (a parse error, etc). This will only show up if the constant is in a different scope, e.g. in a class/namespace. – iainn Nov 03 '17 at 15:12
  • can you post the code? Perhaps it is really not defined at the time you are using it. – Juan Nov 03 '17 at 15:12
  • If its in a class, then you need the appropriate `$this->` or `self::` in front of using it (assuming you are calling it within the class). Or `$obj->` and `Classname::` if outside respectively. – IncredibleHat Nov 03 '17 at 15:13
  • 1
    Being in a class means you have to reference it via its fully qualified name e.g. `ClassName::NAMES["boys"]` (or `self::` from within the class). Actually you always have to reference it by its fully qualified name but in the global scope that's just the name. – apokryfos Nov 03 '17 at 15:13

1 Answers1

8

You can't reference a class constant without prefixing it with either the class name (or with self from within the same class):

<?php
class Foo
{
  const NAMES = [
    'boys' => 'john',
    'girls' => 'sue',
  ];
}

echo Foo::NAMES['boys']; // John

Only constants in global scope can be referenced using just their name.

iainn
  • 16,826
  • 9
  • 33
  • 40