I'm relatively new to PHP, and I'm looking for a way to define certain objects as globally accessible from throughout the project, from multiple PHP scripts.
In Java, if I've to access some objects globally, I define some public class named Globals
, and define the objects that I need to access as static in the Globals
class. I then access those objects wherever I need with: Globals.variable_name
.
So basically, I need to initialize these global objects only once and then use them whenever I need them..
One use case:
I've a class named Logger
that has methods to log certain events in a log file. I need to have 1 Logger
instance/object that can be used by all the PHP scripts in the project, whenever they've to log something. I'd rather not have each PHP script using it's own instance of Logger
.
The naive Java-like approach I tried, that did not work:
I created a public class named Globals
in a separate PHP file (named Globals.php) with one static object of type Logger
, named $logHandle
. I included this PHP file in all other PHP files where I need this Logger
object. I then tried to access this object , using Globals->logHandle
from one of the other PHP scripts. This attempt failed miserably.
Is there some similar approach?
Thanks.