Jump to content

[SOLVED] A couple of problems creating a class that will only allow one object.


Cep

Recommended Posts

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?

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.