我有一个PHP库,我不想编辑它,并通过扩展/重写一些方法实现到我的代码中。但我被束缚住了。例如:
class MomentPHP extends Moment {
public $uniqueSettings;
public function formatJS(){
return parent::format($this->uniqueSettings);
}
}
class Moment {
public function startOf(){
//some code
return $this;
}
}我想这么做:
$momentphp = new MomentPHP();
$dateStart = $momentphp->startof('month')->formatJs();这样做的方法是重写MomentPHP中子类中的所有方法来返回自己。
还有其他简单的方法吗?比如使用_call之类的?
编辑:找到了一种方法:
__call方法在类之间切换。如下所示:
class MomentPHP {
private $instance = null;
public $uniqueSettings;
public function __construct(){
$this->instance = new Moment();
}
public function __call($method,$args){
if(in_array($method, get_class_methods($this))){
call_user_func(array($this,$method),$args);
else
call_user_func(array($this->instance,$method),$args);
return $this;
}
public function formatJS(){
return $this->instance->format($this->uniqueSettings);
}
}
class Moment {
public function startOf(){
//some code
return $this;
}
}还有更好的办法吗?
发布于 2014-11-05 08:06:45
这样做的一个正确方法是:
class MomentPHP {
private $instance = null;
public $uniqueSettings;
public function __construct(){
$this->instance = new Moment();
// settings etc.
}
public function __call($method,$args){
$result = NULL;
if(in_array($method, get_class_methods($this))){
$result = call_user_func(array($this,$method),$args);
else
$result = call_user_func(array($this->instance,$method),$args);
if($result instanceof Moment)
$this->instance = $result;
return $this;
}
public function format(){
return $this->instance->format($this->uniqueSettings);
}
}从方法结果中更新实例是关键操作,使用$this而不是$this->instance可以在每次调用中使用扩展程序类。因此,您可以在父类中使用具有链接能力的其他方法时重写该函数。
https://stackoverflow.com/questions/26737492
复制相似问题