In PHP, we can easy to reference an object in any classes
using singleton, e.g.
$obj = SingletonClass::getInstance();
If I am not using singleton, are there any alternative?
In PHP, we can easy to reference an object in any classes
using singleton, e.g.
$obj = SingletonClass::getInstance();
If I am not using singleton, are there any alternative?
If I am not using a Singleton, are there any alternatives?
Yes, this thing is called Dependency Injection and it has been discussed million times before. Basically that means, you instantiate a class, and then pass its instance around another classes that require it. For example:
$pdo = new PDO(....);
$userGateway = new UserGateway($pdo);
$imageGateway = new ImageGateway($pdo);
As you can see, the same instance is shared across those classes.
I will recommend singleton, but you can try something like that:
$GLOBAL = null;
And every time you would like to initate it:
if ($GLOBAL != null()) {
$GLOBAL = new YourObject();
}
Simply instantiate your object in the global scope. An example follows below:
#file1.php
require_once('file2.php');
$instance = new ClassName();
#file2.php
function do_something()
{
global $instance;
#do stuff with with
}