LoginSignup
32
16

More than 3 years have passed since last update.

PHP dotenvの読み込み方が変わってた

Last updated at Posted at 2019-04-11

dotenv使ってみようと思って日本語の入門記事をいくつかあさりながら、書いてあるとおりに

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

みたいにやってみたけど、どうにも動かない。
サーバーのエラーログを見ると

PHP Catchable fatal error:  Argument 1 passed to Dotenv\\Dotenv::__construct() must be an instance of Dotenv\\Loader, string given, called in /hoge/fuga/file.php on line 17 and defined in /hoge/fuga/vendor/vlucas/phpdotenv/src/Dotenv.php on line 31

みたいなエラーが残っていた。
ん〜〜〜〜〜?と思ってGithub見に行くと、Readmeにこんなことが書いてある

UPGRADING FROM V2
(中略)
Consequently, you will need to replace any occurrences of new Dotenv(...) with Dotenv::create(...), since our new native constructor takes a Loader instance now, so that it can be truly customized if required. (後略)

雑訳: アップデートで仕様が変わったからnew Dotenv(...)じゃなくてDotenv::create(...)を使ってね

ということで、その下のUsageに載っているように

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

としてあげると動いた。dotenvみたいに昔からあるやつでも急に読み込み方が変わったりするんですねー。やっぱり原典に当たるのは大事。勉強になりました。

追記

さらにバージョンアップがあり、新しい読み込み方はこうらしいです。 @enutake さんありがとうございます!

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
32
16
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
16