3

having problems with constants in PHP wondering if someone can explain:

this works

const _ROOT = 'd:/aphp/www';

echo "r="._ROOT;

as does this:

if (true) 
        define('_ROOT','d:/aphp/www');

echo "r="._ROOT;

but this gives the error: Parse error: syntax error, unexpected T_CONST

if (true) 
    const _ROOT = 'd:/aphp/www';

echo "r="._ROOT;

I am using php 5.3.2

Ray S.
  • 1,192
  • 3
  • 15
  • 27

1 Answers1

10

That is because ..

The const keyword must be declared at the top-level scope

From the PHP Docs

Note: As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops or if statements.

Source

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126