为什么私有方法不能与多态一起使用? [英] Why are private methods not working with polymorphism?

查看:151
本文介绍了为什么私有方法不能与多态一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用私有方法继承/多态时遇到了一个问题.

Kind of got a problem using inheritance/polymorphism with private methods.

示例:

class cmsPage{

   private function getBlock(){
       $block = new cmsBlock();
       return $block
   }

   function createBlock(){
       $block = $this->getBlock();
       $block->save();
   }
   //... do various things
}


class specialCmsPage extends cmsPage{

   private function getBlock(){
       $block = new specialCmsBlock();
       return $block
   }

}

自然,我希望specialCmsPage继承cmsPage的所有方法.函数getBlock()应确保添加到specialCmsPage的所有内容块的类型均为specialCmsBlock,而不是cmsBlock.

Naturally I want specialCmsPage to inherit all the methods from cmsPage. The Function getBlock() should make sure all Content Blocks added to specialCmsPage are of type specialCmsBlock and not cmsBlock.

我发现,如果我从类方法中删除私有",它只能按我期望的方式工作,但是我更喜欢使用它们,因为这些方法不应从类外部调用. 在getBlock()方法前面使用"私有"时,specialCmsPage始终会收到一个cmsBlock对象.

I figured out, that it only works they way I expect it if I remove the "private" from the class methods, but I would prefer to use these, because these methods should not be called from outside a class. Upon using "private" in front of the getBlock() method specialCmsPage always receives a cmsBlock Object.

是否可以使用"私有"实现我想要的目标?

Is there a way to achieve what I want using "private"?

推荐答案

也许您正在寻找受保护的? 私有成员仅在声明它们的类中可见. 受保护的成员对班级及其子孙可见.

Perhaps you are looking for protected? private members are visible only to the class in which they are declared. protected members are visible to the class and its descendants.

这篇关于为什么私有方法不能与多态一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆