Search code examples
phplaravelfunctionglobal-variables

Global variable in considered as null in Laravel, but correctly seen in normal PHP


pure-php.php

<?php
`
$var = 'OK!';

function my_function()
{
    global $var;
    echo !is_null($var) ? $var : '$var is null';
}

my_function();

Result:

OK!

Now take a look at this:

app/Helpers/global.php


$var = 'OK!';

function myfunction() {
    global $var;

    echo !is_null($var) ? $var : '$var is null';
}

composer.json

...
"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers/global.php"
    ],
...

Then I did composer dump-autoload.

app/routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    dump('before');

    myfunction();

    dump('after');
});

Result at http://127.0.0.1:8000/

before
$var is null
after

:-/

I'm wondering why we cannot get the value of the variable?


Solution

  • First, in your laravel code it's in a PHP closure or anonymous functions, but in your pure-php.php it's just a normal PHP function. So in order to use the $var you need to do this:

    $var = 'OK!';
    
    Route::get('/', function () use ($var) {
        echo !is_null($var) ? $var : '$var is null';
    });
    

    Second, it does not make any sense to me to have a global variable in the routes file and can be used everywhere. There are many better ways to have global variables if that's what you are asking for.

    Update

    This is the default behavior with Composer autoloading rather than Laravel. It has nothing to do with Laravel. Composer makes every effort not to pollute the global scope during autoloading. If you want to force global variables then you should declare them as global in your config file.

    For example:

    create config/helper.php

    <?php
    
    return [
        'foo' => 'bar',
    ];
    
    

    And then you should do this :

    function myfunction()
    {
        return config('helper.foo');
    }