简体   繁体   English

Laravel-$ _ENV无法在服务提供商中使用

[英]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. 我正在尝试构建一个使用第三方API的应用程序,并且正在使用.env.local.php文件存储敏感信息。 I wasn't having any problems with this method until I added another property to the $_ENV superglobal. 在将另一个属性添加到$ _ENV超全局变量之前,此方法没有任何问题。 I can still access other properties of $_ENV except for the recently added property. 除了最近添加的属性,我仍然可以访问$ _ENV的其他属性。 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)". 但是,我可以在应用程序的其他部分访问新属性,但我需要的服务提供程序类除外,该属性会引发“语法错误,意外的'$ _ENV'(T_VARIABLE)”。

This is more or less my .env.local.php 这或多或少是我的.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'];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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