抽象的私人功能

jon*_*tyc 27 php inheritance abstraction

以下代码将使PHP不高兴,customMethod()是私有的.为什么会这样?可见性是由声明某事物而非定义的地方决定的吗?

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

的template.php:

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

    public function commonMethod() {
        $this->customMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

CustomA.php:

class CustomA extends Template {
    private function customMethod() {
       blah...
    }
}
Run Code Online (Sandbox Code Playgroud)

Main.php

...
$object = new CustomA();
$object->commonMethod();
..
Run Code Online (Sandbox Code Playgroud)

Tes*_*rex 45

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

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

  • 这与C++(我认为Java)的行为方式不同.C++允许纯虚函数(它们相当于抽象函数)是私有的.这很好,因为它允许派生类指定和控制要执行的操作,同时强制只有基类可以选择WHEN来执行它.受保护的抽象函数无法提供相同的保证,因为派生类可以自由地创建调用受保护实现并破坏封装的公共函数. (9认同)
  • 解决方法:您可以在抽象类定义中将`final`关键字添加到受保护的函数中(即`final protected function my_function()`).这将阻止子类重写该函数,尽管子类可以为自己调用该函数(父母的私有函数不会发生这种情况).这是否违背了定义抽象类的目的,是另一天的哲学讨论.(或者,您可以定义一个扩展抽象类的新类,并在那里私有地定义函数.) (3认同)

nik*_*san 5

如果你担心会customMethod在课堂外被叫到,CustomA你可以参加CustomA课堂final

abstract class Template{
    abstract protected function customMethod();

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

final class CustomA extends Template {
    protected function customMethod() {

    }
}
Run Code Online (Sandbox Code Playgroud)