NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP 5 singleton/destructor question

David Mintz dmintz at davidmintz.org
Thu Mar 31 17:59:01 EST 2005


On Thu, 31 Mar 2005, csnyder wrote:

> On Thu, 31 Mar 2005 17:02:06 -0500 (EST), David Mintz
> <dmintz at davidmintz.org> wrote:
> >
> > OK, here is the ugliest workaround you've seen all day.
>
> Testing your code on my server, I have a few observations.
>
> 1) it worked for me BUT I don't have mysqli compiled into this server,
> so I wrote a dummy mysqli class
>
> 2) PHP complained that the __construct() function was private -- why
> is it private?
>

I am stealing liberally from G. Schlossnagle's "Advanced PHP Programming."
The private constructor is to prevent everyone except my class from
instantiating it, and thus make sure the singleton is truly single.


> So I'm guessing that mysqli steps on your destruct() function, and/or
> the private construct() is weird-making.

Let's see what happens when I make the constructor public... nope, same
story.

I have also tried having a mysqli as a static member variable rather than
extending mysqli, and various variations -- in some of which, the
destructor worked too well, i.e., it destroyed the object before all my
code was done using it, because the singleton thing is working.

OK, let's try it with a non-mysqli parent... hmmm. I don't get any
complaints about private constructor in my mysqli subclass, but I do
in this example:

class MySingleton extends ParentClass {

	private static $db = false;
	private function __construct() {
		printf("constructing %s...<br />",__CLASS__);
		parent::__construct();
	}

	public static function getInstance() {

		if (self::$db === false) {
			self::$db = new MySingleton();

		}
		return self::$db;
	}

	function __destruct() {
		// ParentClass has a close() method
		self::$db->close();
	}
}
$instance = MySingleton::getInstance();

...with an nice informative error message. You can't override a method and
give it more restrictive access than the parent method (as w/ Java). I
make the constructor public and it runs fine, destructor and all.

I wonder why I get away with a private constructor in my mysqli subclass.

Thanks,

---
David Mintz
http://davidmintz.org/



More information about the talk mailing list