1

In PHP, how do you define a global constant (using the define method) inside a class? I would like my constant to be defined globally after a class has been instantiated.

Looks like this:

class SomethingToInstantiate
{

    public function __construct()
    {
        define('SOMETHING', 'MORE');
    }
}

SomethingToInstantiate is always instantiated per request, so I could use the SOMETHING constant anywhere.

But it seems not to work since PHP can't find the SOMETHING constant.

I'm trying to do this with my Symfony 2.7 application.

Inside the Kernel's construct method, since the Kernel is always instantiated per request (and even in the console commands). I'm doing this so that I can access the defined constant anywhere in my code.

But why in Kernel? I've previously defined it in app.php, but it's risky because there three files that I need to edit (which I might forget sometime)

  • app.php
  • app_dev.php
  • console

That's why, instead of editing those three files, I settled to define the constant inside the Kernel's constructor.

Now again, if you're wondering, I'm trying to define the root dir as a constant so I can access it anywhere in the application.

Why again? Because I want to be able to parse my custom config files from anywhere in the code, I need the root directory to get the file from /app/config and then parse it.

Then why again? I do not have time to study Custom Config things and somethings, I need to do things quickly!

Why again? I seriously don't want to do this, but there's no other way, the whole codebase sucks! (Yeah, because of the previous development) And I have no time left, lol.

Thoughts?

11
  • Possible duplicate of PHP - define constant inside a class Commented May 24, 2018 at 0:08
  • 1
    :( why use a class with it's lovely scope and namespace ability, and want something back into global pollution? I suggest using a method to obtain the value. getTheValue() { return $this->theValue;} Commented May 24, 2018 at 0:08
  • @ObsidianAge the other question states "and make it so it's visible only when called in a class context" this one is about globaL Commented May 24, 2018 at 0:09
  • 2
    Sounds like you need to create a more complete minimal reproducible example that demonstrates the problem. And add the symfony tag. Commented May 24, 2018 at 0:14
  • 1
    "I'm trying to create the global constant inside the Kernel's construct method" this sounds so bad. I know sometimes we cannot judge on face value of things. If you explain in more detail then you can get an answer, or perhaps a suggestion for a better way Commented May 24, 2018 at 0:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.