dotj6816 2016-11-26 17:13
浏览 36
已采纳

如何将dotenv变量用于一个类?

I just start learning PHP few days ago so forgive me if this question is a newbie one. What is wrong with my declaration of CRAWLER_URI ? The env() isn't working outside a method and I don't know why.

namespace App\Http\Controllers;

use GuzzleHttp\Client; 

class SpotifyController extends Controller
{
    const CRAWLER_URI = env('CRAWLER_URI') . ':' . env('CRAWLER_PORT');

    /**
     * Send a GET to Crawler API
     * @return a json crawled by an external API crawler
     */
    public function fetch()
    {
        $client   = new Client(['base_uri' => self::CRAWLER_URI]);
        $response = $client->request('GET');

        dd($response);
    }
}
  • 写回答

1条回答 默认 最新

  • duankuaizhe8257 2016-12-24 19:19
    关注

    So, the issue here is that you can’t use a function as a class constant value:

    According to the PHP manual:

    The value must be a constant expression, not (for example) a variable, a property, or a function call.

    There are many solutions to this problem, for example, if you really want it to be constant, you could use a define() statement like this:

    define('CRAWLER_URI', env('CRAWLER_URI') . ':' . env('CRAWLER_PORT'));
    

    and access it like this:

    echo CRAWLER_URI;
    

    Another method would be to use a static function:

    private static function CRAWLER_URI() {
        return env('CRAWLER_URI') . ':' . env('CRAWLER_PORT');
    }
    

    and access it like this:

    echo $this->CRAWLER_URI();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b