0

I have a config file that contains a constant array that is to be used globally throughout my script.

const ENV = [
        'project_name' => '*',
        'database' => [
            'db' => '*',
            'username' => '*',
            'password' => '*',
            'host' => 'localhost',
            'port' => '3306',
        ],
        'host' => $_SERVER['HTTP_HOST'],
        'ssl' => ($_SERVER["REQUEST_SCHEME"] == 'https') ? true : false,
    ];

When executing the above, I get the following error:

Fatal error: Constant expression contains invalid operations in */config.php on line 3

The reason why I'm trying to have everything predefined in a constant is really not relevant at this stage as this decision was kind of out of my hands.

Please note, I have other values as well that are to be calculated and dealt with before they can be assigned to the constant. Therefore, would love to get to know of a way to store a value (not address to the variable) in the constant array.

Ameed Aabidi
  • 113
  • 1
  • 10
  • 1
    FWIW, `a == b ? true : false` is redundant and can be replaced with just `a == b`. – deceze May 26 '21 at 11:03
  • 1
    Constant definitions cannot contain expressions. The values of the variables are not known yet at that point. Essentially, this would require PHP code to be interpreted twice; the first time to resolve the variable value and the second time to assign the resolved value to your constant. – El_Vanja May 26 '21 at 11:05
  • @El_Vanja What can be done? Any workarounds for my case? – Ameed Aabidi May 26 '21 at 11:08
  • 1
    See if [`define`](https://www.php.net/manual/en/function.define) is applicable to your use case. – El_Vanja May 26 '21 at 11:09
  • You could set a variable before the const and use that value in your const. Not the cleanest solution, but a possible one – Martijn May 26 '21 at 11:12
  • @El_Vanja Yes, the 'define' statement solved my issue. But any particular reason why the const declaration was spitting out error? It's kinda the same after all, except that 'const' declaration is a bit more elegant to the eye... – Ameed Aabidi May 26 '21 at 11:15
  • @Martijn Your solution didn't work out. It gave the same error. – Ameed Aabidi May 26 '21 at 11:16
  • 2
    Because `const` immediately tries to define and resolve the constant's values. `define` is resolved in runtime, and by then the variable values are resolved as well. – El_Vanja May 26 '21 at 11:20

0 Answers0