Abstract private functions

自作多情 提交于 2019-11-29 02:55:53

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.

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

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() {

    }
}

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.

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