php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #30958 Wrong instance returned with 2 singletons
Submitted: 2004-12-02 11:09 UTC Modified: 2005-02-28 21:20 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: schaa101 at tech dot nhl dot nl Assigned:
Status: Closed Package: Class/Object related
PHP Version: 5.0.2 OS: Windows XP Pro SP2
Private report: No CVE-ID: None
 [2004-12-02 11:09 UTC] schaa101 at tech dot nhl dot nl
Description:
------------
When you use 2 singletons, the second singeleton also returns the instance of the first.
If you change the name of the variables, that store the instance of the singleton class, inside the singletons and make them both unique, the problem is solved though.

Reproduce code:
---------------
http://klaas.fiskaaf.com/singleton-bug.rar

or try

http://klaas.fiskaaf.com/singleton-bug.zip

Expected result:
----------------
Singleton1 - Singleton1
Singleton2 - Singleton2

Actual result:
--------------
Singleton1 - Singleton1
Singleton1 - Singleton2

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-12-02 12:16 UTC] schaa101 at tech dot nhl dot nl
<?php

  class Singleton1
  {
    private $instance = null;
    
    private function __Construct()
    { }
    
    public function & GetInstance()
    {
      if( $this->instance == null )
        $this->instance = new Singleton1();
      
      return $this->instance;
    }
    
    public function Write( $message )
    {
      print "Singleton1 - " . $message;
    }

  }

  class Singleton2
  {
    private $instance = null;
    
    private function __Construct()
    { }
    
    public function & GetInstance()
    {
      if( $this->instance == null )
        $this->instance = new Singleton2();

      return $this->instance;
    }
    
    public function Write( $message )
    {
      print "Singleton2 - " . $message;
    }

  }
  
  class Main
  {
    public function __Construct()
    {
      Singleton1::GetInstance()->Write( "Singleton1" );
      echo "<br/>";
      Singleton2::GetInstance()->Write( "Singleton2" );
    }
  
  }

  new Main();
?>
 [2004-12-16 05:47 UTC] rampant at gmail dot com
If error_reporting(E_ALL) is set, you will see that instead of setting $this in a singleton, $this is set in the Main class. Here is the notice:

Notice: Undefined property: Main::$instance in C:\eclipse\workspace\tmote\tmp_singles.php on line 12

Where line 12 is:
if( $this->instance == null )

Replacing $this->instance with self::$instance and 
private $instance = null;
with,
private static $instance = null;

Will make the code behave as expected.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Dec 26 23:01:28 2024 UTC