簡體   English   中英

靜態類可以擴展非靜態類並訪問其方法嗎?

[英]Can a static class extend a non-static class and access its methods?

我有一個充當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.
    }
}

我該如何解決?

與其嘗試將其包裝為全部被靜態調用,不如創建一個單例實例並調用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM