21309 Posts in 5738 Topics by 2603 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 1303 Views |
-
static variables / singletons

3 September 2010 at 8:18am
Hi,
I'm struggling to create a singleton (i.e. following the proper design pattern for a singleton). My singleton is as follows:
class PlannerService {
private $my_variable;
private $my_other_variable;private static $instance;
private function __construct() {
$this->my_variable = time();
$this->my_variable = time();
}public static function getInstance() {
if ($instance == null) {
$instance = new PlannerService();
}
return $instance;
}public function getMyVariable() {
return $this->my_variable;
}public function getMyOtherVariable() {
return $this->my_other_variable;
}
}When i then call this from my controller as below, every time i call it, it thinks that $instance is null and creates a new object.
$instance = PlannerService::getInstance();
$instance->getMyVariable();Any ideas?
-
Re: static variables / singletons

3 September 2010 at 7:59pm Last edited: 3 September 2010 8:00pm
Replace $instance with self::$instance in your getInstance method
-
Re: static variables / singletons

3 September 2010 at 8:35pm
Unfortunately that has not resolved the issue - i've replaced the getInstance method as below, but self::$instance == still returns true every time
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new PlannerService();
}
return self::$instance;
} -
Re: static variables / singletons

3 September 2010 at 9:00pm
You do realize the static variable is set on a per request basis.
In other words, every time you do a new request the variable will be empty initially, and set only after you first call the getInstance method.How are you testing this code?
Because the new code does indeed use the singleton pattern. -
Re: static variables / singletons

3 September 2010 at 9:07pm
Oh right, so statics do not exist across requests (sorry - i'm a Java developer, so I was hoping static meant the same thing as when working with that!). I'll find a different way to do what I need. Thanks!
-
Re: static variables / singletons

3 September 2010 at 9:15pm
Have a look here to learn more about statics:
http://nl3.php.net/manual/en/language.oop5.static.php
| 1303 Views | ||
|
Page:
1
|
Go to Top |


