Aardo
Aardo

Reputation: 227

I want to understand this piece of PHP code (from a Laravel app.php config file)

I'm learning the basics of PHP and Laravel. I need to understand the syntax of this piece of code taken from a Laravel config file named app.php . I shortened the contents of this file to fit here. I'm only interested in the syntax.

<?php

return [
    'name' => env('APP_NAME', 'Laravel'),
    'env' => env('APP_ENV', 'production'),
    'providers' => [
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
    ],
];
?>

I know what return does in a function. It terminates the function and returns a value. But here it is all by itself returning an array I think. Please correct me if I'm wrong. It returns an associative array where the keys are: name, env, providers. The double arrows assign values to the keys in the array. So for instance env('APP_ENV', 'production'); is assigned as a value to 'env' key.

Another thing is where this return returns the array? Is this file included in some other file?

The other thing I don't understand is the env() call. Is it a built in PHP function? What does it do?

Upvotes: 2

Views: 336

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

Where this return returns the array? Is this file included in some other file?

Laravel reads and then uses the arrays returned by config files in the Illuminate\Config\Repository class.

So, when you read the value with something like config('app.name'), it does:

public function get($key, $default = null)
{
    if (is_array($key)) {
        return $this->getMany($key);
    }

    return Arr::get($this->items, $key, $default);
}

Where $this->items is config data read from config files (the arrays you're talking about). If you curious how and where it Laravel read config files, check the Illuminate\Foundation\Bootstrap\LoadConfiguration class:

protected function loadConfigurationFiles(Application $app, RepositoryContract $repository)
{
    $files = $this->getConfigurationFiles($app);

    if (! isset($files['app'])) {
        throw new Exception('Unable to load the "app" configuration file.');
    }

    foreach ($files as $key => $path) {
        $repository->set($key, require $path);
    }
}

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212422

include can also return a value (in this case an array) that will be assigned to a variable in the script that is doing the include. See the section in the PHP Docs (immediately below the security warning)

Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function.

And look at Example #5


And env() is a Laravel function

The env function retrieves the value of an environment variable or returns a default value

Upvotes: 1

Related Questions