Php 静态类能否扩展非静态类并访问其方法?
我有一个类充当Smarty的包装器,但希望在我的应用程序中静态地使用它 我的设置如下所示:Php 静态类能否扩展非静态类并访问其方法?,php,class,Php,Class,我有一个类充当Smarty的包装器,但希望在我的应用程序中静态地使用它 我的设置如下所示: class Template extends Smarty { public function __constructor() { parent::__constructor(); } public function setSettings() { $this-> some smarty settings here }
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()
来检索它,而不是新建Smarty()
:
静态方法只能调用静态方法。这是绕不开的。当您进入
设置设置时,您希望$this
是什么?没有关联的对象。为什么要静态调用它?相反,您可以创建一个Smarty singleton对象。Eli,请看一看:$Smarty变量是否可以在其他类中静态访问?@s2xi在其他类中,将其检索为$Smarty=Template::getInstance()
,您将拥有相同的对象,它是Template
的静态属性。因此,是的,无论您在哪里检索它,它都是相同的静态对象,但是您必须调用getInstance()
,而不是在调用$smarty
@s2xi的任何地方都使用相同的变量$smarty=Template::getInstance()
当我运行此命令时,您将收到相同的静态实例,它说构造函数必须设置为public@s2xi什么说构造函数必须是公共的?PHP5.1+允许私人构造函数。在任何情况下,如果这种情况继续,您可以更改为公共函数\uuu construct()
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();