K
K
knowledge2018-02-15 23:53:33
PHP
knowledge, 2018-02-15 23:53:33

Can require_once be used in this case?

I have some Kernel class where I am going to store the main application settings and inherit this class by other classes if necessary.
there is a settings property and a file connection where these settings are stored through the constructor, naturally through require_once, since I only need to connect it once

class Kernel {
  public $settings;

  public function __construct() {
    $this->settings = require_once __DIR__.'../config.php';
  }
}

And now I have the Controller and View classes, for example, which inherit the Kernel class, and it turns out that the class that inherits first, in particular the Controller, receives settings from the config file as needed, but when View is launched, it returns boolean true. ..
If you replace require_once with require, then everything is fine, but the file is read as many times as the constructor runs, which is already wrong in itself.
How can I correctly read the config.php file in the case I described?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2018-02-16
@knowledge

class Settings {
  private $settings;
  private static $instance;
  public static getInstance() {
    if (!self::$instance) self::$instance = new self();
    return self::$instance;
  }
  public function getSettings() {
    return $this->settings;
  }
  private function __construct() {
    $this->settings = ...
  }
}

class Kernel {
  protected $settings;
  public function __construct() {
    $this->settings = Settings::getInstance()->gteSettings();
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question