Skip to content
Advertisement

Can I still use global $var inside a function in a laravel view?

I am a beginner in Laravel and I am trying to move an existing Project (in native php) to the laravel framework.

Everything so far is working great, except the part where I am trying to execute static functions from my helper classes.

I got a view called old.php, which looks like this:

$my_global_var = 'Hello';

class TestClass {
    public static function foo(){
        global $my_global_var;
        return $my_global_var;
    }
}

dd(TestClass::foo());

And instead of returning “Hello” like it used to, the function returns null instead.

I know I could just pass $my_global_var as a parameter instead, but as I mentioned before, I am trying to move an existing project to laravel. And that project is full of helper classes like TestClass, that are included at the beginning (or autoloaded) and then used throughout the entire programm.

My Question is: Do I have to rewrite all of my helper classes, or is there a way for me to keep the global $my_global_var; line?

Advertisement

Answer

global $my_global_var; // Here is your answer
$my_global_var = 'Hello';

class TestClass {
    public static function foo(){
        global $my_global_var;
        return $my_global_var;
    }
}

dd(TestClass::foo());
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement