LoginSignup
0
1

More than 5 years have passed since last update.

requireでオブジェクトを受け取る時に、グローバル名前空間を汚さない方法

Posted at

超ウルトラ小ネタ。

requireで別ファイルを読み込んで、そこで生成したオブジェクトを受け取る場合があります。
こんな感じですね。

main.php
$config = require './config.php';
config.php
$config = new Config();

$config->foo();
$config->bar();

return $config;

ただ、これだと$configというのがグローバル名前空間を汚染しちゃいます。
そこで無名関数で括っちゃいましょう。

config.php
return (function () {
    $config = new Config();

    $config->foo();
    $config->bar();

    return $config;
})();

一件落着。
おしまい。

0
1
0

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
0
1