PHP扩展类-私有类的子类方法与父方法重写
我有一个父类(我不想编辑它),它包含一些方法PHP扩展类-私有类的子类方法与父方法重写,php,oop,extends,overriding,Php,Oop,Extends,Overriding,我有一个父类(我不想编辑它),它包含一些方法 class Message { private function createNewMessageSimpleOrAlternativeBody() { ...some code here... } private function createNewMessageRelatedBody($oPart){ ...some code here... } private functio
class Message {
private function createNewMessageSimpleOrAlternativeBody() {
...some code here...
}
private function createNewMessageRelatedBody($oPart){
...some code here...
}
private function createNewMessageMixedBody($oPart){
...some code here...
}
public function ToPart($bWithoutBcc = false)
{
$oPart = $this->createNewMessageSimpleOrAlternativeBody();
$oPart = $this->createNewMessageRelatedBody($oPart);
$oPart = $this->createNewMessageMixedBody($oPart);
$oPart = $this->setDefaultHeaders($oPart, $bWithoutBcc);
return $oPart;
}
}
然后我有另一个类,它在上面扩展,我想在这里添加我的代码
class MessageEx extends Message {
private function createNewMessageSimpleOrAlternativeBody() {
...some code here + additional code...
}
private function createNewMessageRelatedBody($oPart){
...some code here + additional code...
}
private function createNewMessageMixedBody($oPart){
...some code here + additional code...
}
public function ToPart($bWithoutBcc = false)
{
$oPart = $this->createNewMessageSimpleOrAlternativeBody();
$oPart = $this->createNewMessageRelatedBody($oPart);
$oPart = $this->createNewMessageMixedBody($oPart);
$oPart = $this->setDefaultHeaders($oPart, $bWithoutBcc);
return $oPart;
}
}
但是在一个扩展类中,当我尝试使用公共函数ToPart()
时,它告诉我,在那里使用的任何方法都是在父类中声明的,而不是在这个子类中声明的,这是我所期望的,因为每个方法都是私有的,只能在类vis$this
中访问。在这种情况下,编辑的函数不会执行我的代码,因为即使我将它们(子类中的方法)声明为final
或protected
我错过了什么 如果我理解正确,您希望通过尝试在继承的类
MessageEx
中重写现有方法,从Message
向现有方法添加代码
虽然您的代码在技术上可以按发布的方式工作,但是MessageEx
中的方法(例如createNewMessageSimpleOralInternativeBody()
)将无法在Message
中调用它们的挂起项,因为Message
中的方法是私有的。在子类中使用final
或protected
将不起作用
但是您可以使用parent::ToPart(…)
,从消息中调用公共方法ToPart
,然后调用消息中的私有方法
或者,如果这不符合您的代码逻辑,您唯一的其他选择是将Message中的方法更改为受保护的,以便可以在MessageEx中访问它们。请详细描述:1。你想做什么。2.添加您需要的确切错误消息get@ErikKalkoken我已经更新了OP。我的目标是不编辑父类,所以我已经创建了一个子类,我在其中进行了编辑,但当调用我的扩展类时,它显示该类中的方法是在父类中声明的,而不是在该子类中声明的,所以我的代码没有执行(没有错误)。可能与其他问题中的海报相同,这是关于继承在php中的工作方式。除非编辑父类,否则无法从子类(AFAIK)访问它们。@Cemal我已经听说过了。只是想知道我是否在PHP代码中做了一些错误的事情。看起来我需要编辑父类。