简体   繁体   中英

Laravel - $_ENV not working in service provider

I am trying to build a app that uses a third party API and am using .env.local.php files to store sensitive information. I wasn't having any problems with this method until I added another property to the $_ENV superglobal. I can still access other properties of $_ENV except for the recently added property. However I can access the new property in other parts of my application except in the service provider class I need it in, which throws "syntax error, unexpected '$_ENV'(T_VARIABLE)".

This is more or less my .env.local.php

<?php

return array(
    'DB_NAME' => 'placeholder',
    'DB_USER' => 'placeholder',
    'NEW_PROPERTY' => 'test' // Property I can't access in my service provider
);

My service provider:

<?php

class Service {

    protected $new_property = $_ENV['NEW_PROPERTY'];

}

If anyone can provide insight on how I can resolve this situation, I would greatly appreciate the assistance. Thanks in advance!

My solution would be to set this value within the constructor. Like so;

<?php 

class Service {
    protected $new_property;

    public function __construct(){
        $this->new_property = $_ENV['NEW_PROPERTY'];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM