views:

99

answers:

4

Hello Guys,

How will I use an instance of an object that is initially loaded throughout the whole site?

I want $myinstance to be used everywhere.

$myinstance = new TestClass();

Thanks!

+6  A: 

What you are looking for is called the singleton pattern.

If you are deeply into OOP architecture, and want to do things like Unit Testing in the future: Singletons are regarded as an imperfect approach and not "pure" in the sense of OOP. I asked a question on the issue once, and got pretty good results with other, better patterns. A lot of good reading.

If you just want to get started with something, and need your DB class available everywhere, just use a Singleton.

Pekka
A: 

You just need to declare your variable in global scope (for example, in the begginning of your whole code), and when you want to use it inside a function, use the "global" statement. See http://php.net/global.

lfagundes
globals are more evil than eval!
shfx
While using a global would work there are better ways to achieve what the original poster is after.
Alan Storm
A: 

I'm not 100% sure I got what you want to do... but I'll try to answer anyway.

I think you can save it to a session variable, using the serialize/unserialize functions to save/retrieve your class instance. Probably you'd code TestClass as a singleton, but that really depends on what you're trying to do.

For instance:

if (!isset($_SESSION["my_class_session_var"])) // The user is visiting for the 1st time
       {
       $test = new TestClass();
       // Do whatever you need to initialise $test...
       $_SESSION["my_class_session_var"] = serialize($test);
       }
 else   // Session variable already set. Retrieve it
       {
       $test = unserialize($_SESSION['my_class_session_var']);
       }
nico
You don't have to explicitly call serialize()/unserialize(). That happens automagically when you reference the $_SESSION super-global.
simplemotives
Oh, good, I didn't know that! Cheers.
nico
A: 

There is a design pattern called Singleton. In short:

Change __construct and __clone to private, so calling new TestClass() will end up with Error!

Now make a class that will create new instance of your object or return existing one...

Example:

abstract class Singleton
{
  final private function __construct()
  {
    if(isset(static::$instance)) {
      throw new Exception(get_called_class()." already exists.");
    }
  }

  final private function __clone()
  {
    throw new Exception(get_called_class()." cannot be cloned.");
  }

  final public static function instance()
  {
    return isset(static::$instance) ? static::$instance : static::$instance = new static;
  }
}

Then try to extend this class and define static $instance variable

class TestClass extends Singleton
{
  static protected $instance;


  // ... 
}

Now try this:

echo get_class($myinstance = TestClass::instance();
echo get_class($mysecondinstance = TestClass::instance());

Done

shfx