2
我有一个简单的问题。我使用一个实现抽象类的单例。是否有可能把getInstance()方法和变量$ _instance放在抽象类中,而不是我想创建的具体的类?抽象类中的单例php
这里是我的代码:
<?php
class Command_Log extends Command_Abstract {
private static $_instance=null;
public static function getInstance() {
if (self::$_instance==null)
self::$_instance=new self();
return self::$_instance;
}
protected function realExecute() {
}
protected function realSimulate($fileHandle) {
}
}
和
<?php
abstract class Command_Abstract implements Command_Interface {
protected $_data=array();
//private static $_instance=null;
protected $_isExecuted=false;
protected $_execute=false;
public function enableExecute() {
$this->_execute=true;
return $this;
}
protected function __construct() {
}
protected function __clone() {}
public function addData($data) {
array_push($this->_data,$data);
return $this;
}
abstract protected function realExecute();
abstract protected function realSimulate($fileHandle);
public function execute() {
if(!$this->_isExecuted && $this->_execute) {
$this->_isExecuted = true;
$this->realExecute();
}
}
public function simulate() {
$exitSystem = false;
if(!$this->_isExecuted && $this->_execute) {
$this->_isExecuted = true;
$exitSystem = $this->realSimulate($fh);
}
}
return $exitSystem;
}
}
我有命令的许多实现,所以我不想重复代码无处不在我的实现。是否有可能把这两样东西放在抽象类中,如果是的话请告诉我如何。
如果不是,请向我解释为什么它不是possbile。或者,如果我需要改变一些事情来做到这一点,无论如何。
关于
+1,贡献虽然当你说“也有在PHP 5.2的一些问题”,你的意思是“这在PHP 5.2中是不可能的!“!对于任何不知道的人来说,新功能是[后期静态绑定](http://php.net/manual/en/language.oop5.late-static-bindings.php),并且在所有各种使PHP的OOP支持更加灵活的方法。 – lonesomeday 2010-10-07 20:34:15
实际上代码是为5.2制作的。我使用了一个函数来模拟函数get_called_class()http://www.septuro.com/2009/07/php-5-2-late-static-binding-get_called_class-and - self-new-self /而不是使用self :: initialize的静态绑定我使用$ this-> initialize(这就是为什么我在Singleton类中评论该行)我不确定这样做是否正确,但它适用于5.2 =) – pleasedontbelong 2010-10-07 20:43:19
很好,非常感谢,我注定要使用5.2我已经使用了一些5.3特性,如$ var :: call_method(),并且必须将它返回给call_user_func(array($ var,“call_method “)),因为我意识到我需要5.2的支持。我会看看是否真的想为你的解决方案做5.2。不要误会我的意思,它的美丽,但可能不是我想要走路的方式。 :) – evildead 2010-10-07 21:08:09