Cep Posted January 25, 2008 Share Posted January 25, 2008 Hi, I am trying to create a class were only one object will be allowed to be instantiated at a single point in time. This is the first crack at this kind of thing before and I am getting an unexpected problem which I know must be something I am doing wrong. What the code should do is create an object from a static call, check a static counter and if the counter is 0, create the object. If not create nothing. The $counter and __construct are both private for obvious reasons, I don't want anyone directly instantiating the class, I have not dealt with cloning just yet but I don't want to overcomplicate things. The problem I have is twofold, firstly the code doesn't appear to work, and I will show you why and secondly I want to display $counter's value without making it public so I assign its value to $count which is public but if changed would not affect my object instantiation counter. <?php class Order { private static $counter = 0; public static $count = 0; public $name = ""; private function __construct() { echo "I am now an object, "; self::$count = self::$counter; } public static function createMe() { if (self::$counter===0) { $object = new Order(); self::$counter++; return $object; } else { echo "I cannot be created, "; return NULL; } } public function __destruct() { self::$counter--; } } $myobject = Order::createMe(); $myobject->name = "hello my name is Barney<br />"; echo $myobject->name; echo "The object counter is currently: ".Order::$count."<br />"; $newobject = Order::createMe(); $newobject->name = "hello my name is Smit<br />"; echo $newobject->name; echo "The object counter is currently: ".Order::$count."<br />"; ?> The output is, I am now an object, hello my name is Barney The object counter is currently: 0 I cannot be created, hello my name is Smit The object counter is currently: 0 Which is kind of wrong because how is the Smit line getting added to a non-object, unless that object exists? Quote Link to comment Share on other sites More sharing options...
emehrkay Posted January 25, 2008 Share Posted January 25, 2008 I think that self::counter will always be zero when called outside of an instantiated object You should look into a singleton patten (you're basically doing one) http://en.wikipedia.org/wiki/Singleton_pattern#PHP_5 Quote Link to comment Share on other sites More sharing options...
Cep Posted January 25, 2008 Author Share Posted January 25, 2008 Lol thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.