Php 如何获取父类实例?
我有两门课: Singleton.phpPhp 如何获取父类实例?,php,Php,我有两门课: Singleton.php namespace Core\Common; class Singleton { protected static $_instance; private function __construct(){} private function __clone(){} public static function getInstance() { if (null === self::$_instance)
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');
但出现错误:“调用未定义的方法Core\Common\Singleton::setConfig()
正如我所看到的getInstance()返回我的Singleton类实例,而不是Config,我如何从Singleton返回Config实例 您可以将
getInstance
更改为:
public static function getInstance() {
if (!isset(static::$_instance)) {
static::$_instance = new static;
}
return static::$_instance;
}
突出显示了self
和static
之间的区别:
self是指新操作在其方法中发生的同一类
PHP5.3后期静态绑定中的static是指层次结构中调用方法的任何类
这意味着它是动态地绑定到扩展类的,因此在您的例子中,newstatic
引用Config
类,使用self
将始终静态地引用Singleton
类
正在工作。
getInstance
是singleton
中的静态方法。这是实例化自身,因此没有Config的实例。重载配置中的getInstance
,然后从那里使用它,但我不希望在所有单例类中都使用双副本getInstance代码,真的没有其他方法吗?它可以工作。谢谢你,哥们儿)迟了的静电装订,为什么我不考虑呢?不客气,我第一次用它的时候也给了我一个惊喜。