Dotenv\Loader::getEnvironmentVariable PHP Method

getEnvironmentVariable() public method

Search the different places for environment variables and return first value found.
public getEnvironmentVariable ( string $name ) : string | null
$name string
return string | null
    public function getEnvironmentVariable($name)
    {
        switch (true) {
            case array_key_exists($name, $_ENV):
                return $_ENV[$name];
            case array_key_exists($name, $_SERVER):
                return $_SERVER[$name];
            default:
                $value = getenv($name);
                return $value === false ? null : $value;
                // switch getenv default to null
        }
    }

Usage Example

Example #1
0
 /**
  * Assert that the callback returns true for each variable.
  *
  * @param callable $callback
  * @param string   $message
  *
  * @return \Dotenv\Validator
  */
 protected function assertCallback($callback, $message = 'failed callback assertion')
 {
     if (!is_callable($callback)) {
         throw new \InvalidArgumentException('Callback must be callable');
     }
     $variablesFailingAssertion = array();
     foreach ($this->variables as $variableName) {
         $variableValue = $this->loader->getEnvironmentVariable($variableName);
         if (call_user_func($callback, $variableValue) === false) {
             $variablesFailingAssertion[] = $variableName . " {$message}";
         }
     }
     if (count($variablesFailingAssertion) > 0) {
         throw new \RuntimeException(sprintf('One or more environment variables failed assertions: %s', implode(', ', $variablesFailingAssertion)));
     }
     return $this;
 }