抽象的私人功能 [英] Abstract private functions

查看:123
本文介绍了抽象的私人功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将让PHP感到不满,即customMethod()是私有的。为什么会这样?可见性是根据声明的内容而不是定义来确定的吗?

The following code will have PHP unhappy that customMethod() is private. Why is this the case? Is visibility determined by where something is declared rather than defined?

如果我想使customMethod只对Template类中的样板代码可见并防止它被覆盖,那么我只是让它保护并最终?

If I wanted to make customMethod only visible to boilerplate code in the Template class and prevent it from being overriden, would I just alternatively make it protected and final?

Template.php:

Template.php:

abstract class Template() {
    abstract private function customMethod();

    public function commonMethod() {
        $this->customMethod();
    }
}

CustomA.php:

CustomA.php:

class CustomA extends Template {
    private function customMethod() {
       blah...
    }
}

Main.php

...
$object = new CustomA();
$object->commonMethod();
..


推荐答案

抽象方法不能是私有的,因为根据定义,它们必须由派生类实现。如果您不希望它是 public ,则需要 protected ,这意味着可以看到它通过派生类,但没有其他人。

Abstract methods cannot be private, because by definition they must be implemented by a derived class. If you don't want it to be public, it needs to be protected, which means that it can be seen by derived classes, but nobody else.

The关于抽象类的PHP手册以这种方式向您展示了使用 protected 的示例。

The PHP manual on abstract classes shows you examples of using protected in this way.

这篇关于抽象的私人功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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