ecco
ecco

Reputation: 516

extends a singleton class in PHP

<?php
class LoveBase
{
    protected static $_instance = NULL;
    protected function __construct() {}
    public static function app()
    {
        if(self::$_instance == NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function get()
    {
        return 'LoveBase';
    }

}

class Love extends LoveBase
{
    public static function app()
    {
        if(self::$_instance == NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    public function get()
    {
        return 'Love';
    }
}

// Print "LoveLove" in this case(first case)
echo Love::app()->get(); 
echo LoveBase::app()->get();

// Print "LoveBaseLoveBase" in this case(second case)
// echo LoveBase::app()->get();
// echo Love::app()->get();
  1. Why the two different method come out the same result?

  2. Compare the two case, the method will work when it's class instantiate first.

(Sorry, I am not good at english, hopefully you can make sence)

Upvotes: 1

Views: 151

Answers (2)

Niko
Niko

Reputation: 26730

You define two static functions, that both use the same static variable ($_instance) - a static member of the base class can also be access via subclasses (as long as it is not private). Remember that static stuff (methods and variables) gets inherited, but not cloned.

Solution: Make the member variable private, and create one per class.

class LoveBase
{
    private static $_instance = NULL;
    // ...

class Love extends LoveBase
{
    private static $_instance = NULL;
    // ...

Upvotes: 3

Ziumin
Ziumin

Reputation: 4860

// Print "LoveLove" in this case(first case)

//Set self::$_instance to Love object id
echo Love::app()->get(); 

//Static property $_instance is now already set, so LoveBase::app() won't create new self(), it will just return created and saved Love object
echo LoveBase::app()->get();

// Print "LoveBaseLoveBase" in this case(second case)

// Here is the same case, but static property $_instance filled with new self() in LoveBase class
// echo LoveBase::app()->get();
// echo Love::app()->get();

Upvotes: 0

Related Questions