Constant expressions in PHP 5.5 or before

91 views Asked by At

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?

1

There are 1 answers

1
shingo On BEST ANSWER

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;
}