0

I wonder, what are the pros and the cons of these two approaches to access variables:

1) CodeIgniter -style (does this have a name?)

public function doSomething()
{
 $database = $this->database; // or just $this->database
}

2) The Singleton pattern

public function doSomething()
{
 $database = Framework_Database::getInstance();
}

One obvious difference is that with Singleton, you can't modify it. You can only access it, but I'm talking about here only in the aspect of accessing an instance of a class or a variable.

Oh, and, are there other approaches?

Fionnuala
  • 90,370
  • 7
  • 114
  • 152
Tower
  • 98,741
  • 129
  • 357
  • 507

1 Answers1

3

These two methods of getting a reference to an existing instance aren't really mutually exclusive. The first is assuming that the doSomething() method is contained in a class which also contains a $database field, which has been set to a Database instance (maybe through the class constructor). That initial setting of the $this->database may very well have been through the use of a singleton's getInstance() method.

I suppose then that you could compare the two on whether or not you would keep a reference to the instance as a field of the class or always request a new reference directly from the Singleton. I can't think of a time where this wouldn't come down to simply preference, though definitely pick one and stick with it. (personally, I would choose the second for separation of concerns)

Most importantly, consistency in the patterns you use in your code will go a long way toward decreasing maintenance costs.

James Maroney
  • 3,136
  • 3
  • 24
  • 27