Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variable in laravel

Tags:

In PHP, I used to define some variables in my header.php and use them in all my pages. How can I have something like that in Laravel?

I am not talking about View::share('xx', 'xx' );

Assume I want to have a variable which holds a number in it and I need this number inside all my controllers to calculate something.

like image 651
Pars Avatar asked Nov 06 '13 09:11

Pars


People also ask

What is global variable in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Should I use global variables in PHP?

There is no need to do global $variable; to access it within functions or methods. Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.


2 Answers

Sounds like a good candidate for a configuration file.

Create a new one, let's call it calculations.php:

Laravel ~4ish:

app     config         calculations.php 

Laravel 5,6,7+:

config     calculations.php 

Then put stuff in the new config file:

<?php return [ 'some_key' => 42 ]; 

Then retrieve the config in your code somewhere (note the file name becomes a "namespace" of sorts for the config item):

echo Config::get('calculations.some_key'); // 42 in Laravel ~4 echo config('calculations.some_key'); // 42 in Laravel ~5,6,7+ 
like image 99
fideloper Avatar answered Oct 16 '22 10:10

fideloper


Set a property on the BaseController, which should be located in your controllers directory.

Your controllers should extend the BaseController class and thus inherit its properties.

like image 31
Jacob Avatar answered Oct 16 '22 11:10

Jacob