Vladimir Gordienko
Vladimir Gordienko

Reputation: 3470

How to get parent class instance?

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?

Upvotes: 4

Views: 3007

Answers (1)

Ende Neu
Ende Neu

Reputation: 15783

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.

Upvotes: 3

Related Questions