On Tue, 11 Nov 2003 23:50:24 +0100,
hs*@freecode.dk (Henrik S. Hansen) wrote:
I'm trying to create a singleton (only one instance of a class), but
this doesn't work, can anyone explain this?
<code>
function &get_instance()
{
static $instance;
if (! isset($instance))
{
echo "test";
$instance =& new Foo();
}
return $instance;
}
</code>
It get called like this: $bar =& Foo::get_instance();
I've seen examples on the web, saying this should work. What am I doing
wrong?
It appears to me from the code below that you can't assign by reference to a
static variable? (maybe)
The only difference between Foo::get_instance and Foo::get_instance2 is
missing the & on the assignment to $instance.
Digging a bit further through the manual finds that this is documented, see
the end of:
http://www.php.net/manual/en/languag...bles.scope.php
<pre>
<?php
class Foo
{
function Foo()
{
echo "Foo constructor\n";
}
function &get_instance()
{
static $instance;
var_dump($instance);
if (!isset($instance))
{
echo "test\n";
$instance =& new Foo();
}
var_dump($instance);
return $instance;
}
function &get_instance2()
{
static $instance;
var_dump($instance);
if (!isset($instance))
{
echo "test\n";
$instance = new Foo();
}
var_dump($instance);
return $instance;
}
}
$bar =& Foo::get_instance();
$bar =& Foo::get_instance();
$bar =& Foo::get_instance();
echo "\n";
$bar =& Foo::get_instance2();
$bar =& Foo::get_instance2();
$bar =& Foo::get_instance2();
?>
</pre>
Output:
NULL
test
Foo constructor
object(foo)(0) {
}
NULL
test
Foo constructor
object(foo)(0) {
}
NULL
test
Foo constructor
object(foo)(0) {
}
NULL
test
Foo constructor
object(foo)(0) {
}
object(foo)(0) {
}
object(foo)(0) {
}
object(foo)(0) {
}
object(foo)(0) {
}
--
Andy Hassall (an**@andyh.co.uk) icq(5747695) (
http://www.andyh.co.uk)
Space: disk usage analysis tool (
http://www.andyhsoftware.co.uk/space)