Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rvkvino's avatar

Accessing environment variable in my custom class

I have created class inside of app folder. I'm using lumen 5.5, I have declared variable in .env file as like MSG91_KEY=7214AyBG34545K56ff4bcb MSG91_SENDER_ID=LOGIMX MSG91_ROUTE=4

I have tried to access this on my custom class like below, but say not defined private $API_KEY = env("MSG91_KEY");

Is there any other restriction using env variables in the custom class.

0 likes
3 replies
click's avatar
click
Best Answer
Level 35

I expect your class looks something like this:

class YourClass
{
    private $API_KEY = env('MSG91_KEY'); 
}

This is not allowed in PHP. You can't call functions as default values for a class property.

There are multiple solutions but you could set the api key from within the class constructor

class YourClass
{
    private $api_key;

    public function __construct() {
         $this->api_key = env('MSG91_KEY');
    } 
}
1 like
tykus's avatar

Where do you have this in your custom class?

private $API_KEY = env("MSG91_KEY");
rvkvino's avatar

As m-rk said I have changed declaration and assignment, now it is working. Thanks for your reply.

Please or to participate in this conversation.