1

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?

8
  • 4
    I cannot make sense of the question. Commented Aug 19, 2014 at 9:55
  • Store it in a variable? What are you asking here? Commented Aug 19, 2014 at 9:55
  • He's asking if it's possible to check if there's already an instance of an object without using the singleton pattern - i guess Commented Aug 19, 2014 at 9:56
  • 1
    go through every single entry in the $GLOBALS and evaluate whether its an INSTANCEOF ClassName ?! Commented Aug 19, 2014 at 9:57
  • It would be interesting to know WHY you don't / can't use singleton ? Commented Aug 19, 2014 at 10:02

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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();
}

2 Comments

i wouldn't override the $GLOBAL variable...
@RaggaMuffin-420 That's not a $GLOBAL, but $GLOBALS
-2

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
}

3 Comments

wow just wow. Globals are never a solution. Especially not when the question is tagged OOP
@PeeHaa if you read his question, you'd realise he was searching for a way to use a single object instance, without making the class a Singleton. 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.