Reputation: 81
I am in the infant stages of my web development career and have a quick question.
I have a variable I am using in a lot of my controller's functions.
$today = new DateTime('today');
I have read that declaring global variables is a big no no and I would like to get away from having to declare it in each function.
What would be the best way to declare this variable and use it across all of my controllers functions?
Upvotes: 0
Views: 478
Reputation: 87719
If this is something you are using on your controllers only, you can just create it in a base controller:
<?php
BaseController extends Controller {
protected $today;
public function __construct()
{
$today = new DateTime('now');
}
}
MyController extends BaseController {
public function whatever()
{
echo "today: $this->today";
}
}
If this is something you need in your views, you can use:
View::share('today', new DateTime('now'));
And it will be available to all your views:
Today: {{ $today }}
This doesn't make much sense to me, but if you want to keep this variable between requests, you can use the laravel Session Facade:
Session::put('today', now DateTime('now'));
echo Session::get('today');
Don't use $_SESSION
unless you really need to take control over session handling.
Upvotes: 3
Reputation: 719
You can use $_SESSION
variables to store data and still have global usage.
session_start();
$_SESSION['today'] = new DateTime('today');
Upvotes: 0