How can we use \Drupal
class inside the settings.php file to load configuration ojects, for example?
$slogan = \Drupal::config('system.site')->get('slogan');
There is no config available when settings.php is executed. This is in very early stages of the Drupal bootstrap process and neither the database connection nor the service container is initialized.
The settings.php file is loaded from DrupalKernel::initializeSettings()
, which is called from DrupalKernel::handle()
before DrupalKernel::boot()
.
This means that when the code in settings.php is executed, the dependency injection container hasn't yet initialized, the services aren't yet available, and \Drupal::config()
would throw an exception about \Drupal::$container
not yet initialized.
The code in the settings.php file can use PHP functions or functions/methods already loaded from the autoloader. The latter aren't guaranteed to function properly.
The purpose of the settings.php file is (generally speaking) setting configuration values.
It could read some configuration values from its local variables, for example $settings['hash_salt']
or $settings['file_public_base_url']
, but code that would work in a module isn't guaranteed to work in the settings.php file.
\Drupal
class is calling the bootstrapped system, which of course can't be done without loading the settings. So you're in a loop. As leymannx asked, what are you trying to do?