【问题标题】:PHP extended class - subclass method vs parent method overriding for privatePHP扩展类-子类方法与父方法覆盖私有
【发布时间】:2018-07-08 11:29:33
【问题描述】:

我有一个包含一些方法的父类(我不想编辑它)

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() 时,它告诉我在那里使用的任何方法都在父类中声明,而不是在这个子类中,我期望这是因为它们每个都是私有的并且 只能在 $this 的类中访问。在这种情况下,编辑的函数不会执行我的代码,因为即使我将它们(子类中的方法)声明为 final 或 protected

我错过了什么?

【问题讨论】:

  • 请详细描述: 1. 你想做什么。 2. 添加您收到的确切错误消息
  • @ErikKalkoken 我已经更新了 OP。我的目标是不编辑父类,所以我创建了一个子类,在那里我完成了我的编辑,但是当调用我的扩展类时,它显示该类中的方法是在父类中声明的,而不是在那个子类中,所以我的代码没有被执行(没有错误)。
  • 正如其他问题中提到的海报,它是关于继承如何在 php 中工作的。除非您编辑父类,否则您无法从子类 (AFAIK) 访问它们。
  • @Cemal 这就是我已经听说过的。只是想知道我是否在 PHP 代码中做错了什么。看起来我需要编辑父类。

标签: php oop extends overriding


【解决方案1】:

如果我对您的理解正确,您希望通过尝试在您的继承类 MessageEx 中覆盖它们来将代码添加到来自 Message 的现有方法。

尽管您的代码在技术上可以按照发布的方式工作,但您在 MessageEx 中的方法(例如 createNewMessageSimpleOrAlternativeBody() )将无法调用它们在 Message 中的挂件,因为 Message 中的方法是私有的。在子类中使用final 或protected 将不起作用。

但是你可以做的是用parent::ToPart(..)从Message调用公共方法ToPart,这反过来又会调用Message中的私有方法。

或者,如果这不符合您的代码逻辑,您唯一的其他选择是将 Message 中的方法更改为 protected,以便它们可以在 MessageEx 中访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2014-11-22
    • 2017-11-18
    相关资源
    最近更新 更多