4

I have two classes:

Singleton.php

namespace Core\Common;

class Singleton
{
    protected static $_instance;

    private function __construct(){}
    private function __clone(){}

    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

Config.php

namespace Core;

class Config extends Common\Singleton
{

    private $configStorage = array();    

    public function setConfig($configKey, $configValue)
    {
        $this->configStorage[$configKey] = $configValue;
    }

    public function getConfig($configKey)
    {
        return $this->configStorage[$configKey];
    }   
}

my index.php

require_once 'common\Singleton.php';
require_once 'Config.php';
$config = \Core\Config::getInstance();
$config->setConfig('host', 'localhost');

but got the error: "Call to undefined method Core\Common\Singleton::setConfig()"

So as i can see getInstance() return me Singleton class instance, but not Config, how i can return Config instance from Singleton?

Vladimir Gordienko
  • 3,260
  • 3
  • 18
  • 25
  • `getInstance` is a static method in `singleton`. This is instantiating itself, thus there's no instance of Config. Overload `getInstance` in Config and use it from there then – Axel Amthor Aug 24 '14 at 06:49
  • but i dont want diblicate getInstance code in all singleton classes, really there is no other way? – Vladimir Gordienko Aug 24 '14 at 06:52

1 Answers1

3

You can change your getInstance to this:

public static function getInstance() {
    if (!isset(static::$_instance)) {
        static::$_instance = new static;
    }
    return static::$_instance;
}

The difference between self and static is highlighted here:

self refers to the same class whose method the new operation takes place in.

static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.

So it means that is bounded dynamically to the extending class, hence new static in your case refers to the Config class, using self will always statically refers to the Singleton class.

Working example here.

Community
  • 1
  • 1
Ende Neu
  • 15,581
  • 5
  • 57
  • 68