Short-hand PHP Dotenv instantiation

This post is more than 18 months old. Since technology changes to rapidly, this content may be out of date (but that's not always the case). Please remember to verify any technical or programming information with the current release.

I’m a big fan of PHP DotEnv for creating my environment variables for my scripts. (It’s always a good thing to keep your passwords and credentials separate from your source code, according to OWASP).

Now, this is kind of nit-picky, but I never liked the instructions from phpdotenv on how to initialize their code. This is what they say to do:

$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();

Ok - so that’s not that big of a deal. But, since programmers are lazy and we like to make things even quicker, I decided to use one of PHP 5.4’s new features in my code: Class member access on instantiation.

Now, my PHP code looks super simple - just like this:

(new Dotenv\Dotenv(__DIR__))->load();
php

Return to All Posts