Re: singleton

From: Date: Fri, 21 Jun 2002 06:15:13 +0000
Subject: Re: singleton
References: 1  Groups: php.dev 
Request: Send a blank email to php-dev+get-85428@lists.php.net to get a copy of this message
Purushotham Komaravolu wrote: > Is there any way to create a singleton in Php4? Yes, but this is the wrong list to ask such questions. Anyhow: PHP 4 <?php class Singleton { function &getInstance() { static $instance; if (!isset($instance)) { echo "Creating new object.\n"; $instance = new Singleton; } return $instance; } } $a = Singleton::getInstance(); $b = Singleton::getInstance(); if ($a === $b) { echo '$a and $b reference the same object.' . "\n"; } ?> PHP 5 <?php class Singleton { static $instance = null; function getInstance() { if (self::$instance == null) { echo "Creating new object.\n"; self::$instance = new Singleton; } return self::$instance; } } $a = Singleton::getInstance(); $b = Singleton::getInstance(); if ($a === $b) { echo '$a and $b reference the same object.' . "\n"; } ?> -- Sebastian Bergmann http://sebastian-bergmann.de/ http://phpOpenTracker.de/ Did I help you? Consider a gift: http://wishlist.sebastian-bergmann.de/

« previous php.dev (#85428) next »