34

我正在使用一组类的接口。但是我有一个问题,因为我希望visibility在界面中允许任何内容(即:publicprotectedprivate

我只需要保护父方法,我需要私有子方法,但我收到错误消息

致命错误:接口方法 Baz::qux() 的访问类型必须在 <the file with Baz/Bar> 中省略。"

我尝试在界面中指定其他可见性方法Baz并删除public,但它们都失败了。

有没有办法通过界面来做到这一点?如果没有,那么有没有办法可以声明它abstract,我也尝试过,但失败了。

interface Baz
{
    public function qux();
}

class Bar implements Baz
{
    protected function qux()
    {
        //do foo
    }
}

class Foo extends Bar implements Baz
{
    private function qux()
    {
        parent::qux();
    }
}
4

3 回答 3

58

Methods you declare in Interfaces should be public. You define a contract with an interface. Any non-public methods would be implementation details and those do not belong into an Interface. As the name implies implementation details should go into the concrete classes implementing the interface.

From Wikipedia:

Programming to the interface

The use of interfaces allows a programming style called programming to the interface. The idea behind this is to base programming logic on the interfaces of the objects used rather than on internal implementation details. Programming to the interface reduces dependency on implementation specifics and makes code more reusable.[7] It gives the programmer the ability to later change the behavior of the system by simply swapping the object used with another implementing the same interface.

于 2012-10-15T15:05:54.943 回答
18

A interface is a contract between 2 parties, a agreement how they communicate.

It makes no sense to make methods protected or private, because the other party will not see those.

于 2012-10-15T15:06:23.430 回答
0

The devs disabled the visibility for more fluid reusage. Through the keyword implements you already bind an interface to a class. You cannot access an interface without having it implemented anyways.

于 2016-09-13T13:15:27.000 回答