静态类可以扩展非静态类并访问其方法吗?

时间:2012-01-18 18:58:53

标签: php class

我有一个类充当Smarty的包装器,但想要在我的应用程序中静态使用它。

我的设置看起来像这样:

class Template extends Smarty {

    public function __constructor() {

         parent::__constructor();
    }

    public function setSettings() {

         $this-> some smarty settings here
    }

    public static function loadTpl($tpl) {

         self::$tplFile = $tpl;

         // other logic

         self::setSettings(); // this won't get executed because it uses non static method calls.
    }
}

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

不是尝试将其包装为静态调用,而是创建单例实例并调用Template::getInstance()来检索它而不是new Smarty()

class Template extends Smarty {
  public static $instance = NULL;

  // Private constructor can't be called
  private function __construct() {
    parent::__construct();
  }

  // Instead instantiate or return the existing instance
  public static function getInstance () {
    return self::$instance ? self::$instance : new self();
  }
}


// Instantiate as:
$smarty = Template::getInstance();