When two singletone classes calls getInstace methods of each other

Discussion in 'PHP' started by debong, Sep 29, 2009.

  1. #1
    Hi. Have you ever had such problem when two different classes gets each other instances in their constructors. In this case PHP always does not see a static variable which should keep an object. And some kind of infinite recursion starts which causes that php returns nothing (i think because it kills a thread).

    The code:
    class first
    {
        static function &getInstance()
        {
            static $instance;
            if (!isset($instance)) 
            {
                $instance = new first();
            }
            return $instance;
        }
        
        function __construct()
        {
            echo 'initiated '.__CLASS__.'<br />';
            $s = &second::getInstance();      
        }
    }
    
    class second
    {
        static function &getInstance()
        {
            static $instance;
            if (!isset($instance)) 
            {
                $instance = new second();
            }
            return $instance;
        }
        
        function __construct()
        {
            $f = &first::getInstance();
            echo 'initiated '.__CLASS__.'<br />';    
        }
    }
    
    $f = &first::getInstance();
    $s = &second::getInstance();
    
    $f = &first::getInstance();
    $s = &second::getInstance();
    
    PHP:
    The same example with $GLOBALS

    class first
    {
        static function &getInstance()
        {
            if (!isset($GLOBALS['first'])) 
            {
                $GLOBALS['first'] = new first();
            }
            return $GLOBALS['first'];
        }
        
        function __construct()
        {
            echo 'initiated '.__CLASS__.'<br />';
            $s = &second::getInstance();      
        }
    }
    
    class second
    {
        static function &getInstance()
        {
    
            if (!isset($GLOBALS['second'])) 
            {
                $GLOBALS['second'] = new second();
            }
            return $GLOBALS['second'];
        }
        
        function __construct()
        {
            $f = &first::getInstance();
            echo 'initiated '.__CLASS__.'<br />';    
        }
    }
    
    
    $f = &first::getInstance();
    $s = &second::getInstance();
    PHP:
    In bouth cases (using static or $GLOBALS) starts to work normally only when a line with getInstance is commented in one of the classes.

    PHP version 5.2.8 WAMP
     
    Last edited: Sep 29, 2009
    debong, Sep 29, 2009 IP