Search code examples
phpphpdotenv

How to use dotenv variables into a class?


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);
    }
}

Solution

  • 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();