1

I'm working on a legacy PHP codebase that runs on PHP 5.4. I want to derive class-specific constants or properties based on a common constant. So for instance in PHP 5.6 or later I'd do:

config.php

define('CONFIG_DIR', 'PATH_TO_CONFIG_DIR');

MyClass.php

class MyClass {
     const FILE_A = CONFIG_DIR . '/fileA';
     const FILE_B = CONFIG_DIR . '/fileB';
}

But constant expressions are only allowed since PHP 5.6.

https://www.php.net/manual/en/migration56.new-features.php

So in PHP 5.4 what are the options that I could follow to derive sub-values based on a common constant within the class?

Raptor
  • 53,206
  • 45
  • 230
  • 366
Gayan Weerakutti
  • 11,904
  • 2
  • 71
  • 68

1 Answers1

4

define could be an option.

define('CONFIG_DIR', 'PATH_TO_CONFIG_DIR');
define('CONFIG_DIR_FILE_A', CONFIG_DIR . '/fileA');
define('CONFIG_DIR_FILE_B', CONFIG_DIR . '/fileB');
class MyClass {
     const FILE_A = CONFIG_DIR_FILE_A;
     const FILE_B = CONFIG_DIR_FILE_B;
}
shingo
  • 18,436
  • 5
  • 23
  • 42
  • To obtain the constant `FILE_A` from `MyClass`, [Relection](https://www.php.net/manual/en/book.reflection.php) can be used in PHP 5.4: `$c = new ReflectionClass('MyClass'); echo $c->getConstants()['FILE_A'];` – Raptor Nov 21 '22 at 07:03