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();
}
$GLOBAL variable...$GLOBAL, but $GLOBALSSimply 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
}
Globals are never a solution. Especially not when the question is tagged OOPSingleton. Globals are the cleanest way to do that, so long as the developer stays aware of what he's declared. So you know, the question is tagged OOP because he's interested in Classes and Objects.
singleton pattern- i guess$GLOBALSand evaluate whether its anINSTANCEOF ClassName?!