Abstract private functions

吃可爱长大的小学妹 提交于 2019-11-30 07:20:34

问题


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?

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:

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

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

CustomA.php:

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

Main.php

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

回答1:


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 manual on abstract classes shows you examples of using protected in this way.




回答2:


Abstract method's are public or protected. This is a must.




回答3:


If you fear that customMethod will be called outside of the CustomA class you can make the CustomA class final.

abstract class Template{
    abstract protected function customMethod();

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

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

    }
}



回答4:


Nothing in PHP that is private in a child class is visible to a parent class. Nothing that is private in a parent class is visible to a child class.

Remember, visibility must flow between the child class up to the parent class when using abstract methods in PHP. Using the visibility private in this scenario with PHP would completely encapsulate CustomA::customMethod inside of CustomA. Your only options are public or protected visibility.

Since you cannot make an instance of the abstract class Template, privacy from client-code is maintained. If you use the final keyword to prevent future classes from extending CustomA, you have a solution. However, if you must extend CustomA, you will have to live with how PHP operates for the time being.



来源:https://stackoverflow.com/questions/7939199/abstract-private-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!